FarSoft Group
FarSoft Group

Reputation: 59

Find key of an array in another array

I have an array like this:

Array ( [0] => Array ( [pid] => 8 [bv] => 0 [bs] => 0 ) [1] => Array ( [pid] => 11 [bv] => 0 [bs] => 0 ) [2] => Array ( [pid] => 10 [bv] => 0 [bs] => 0 ) ) 

as you see this array includes other arrays. Now I want to delete array with [pid] = 8 , for deleting that I need that array key but I don't know how to find the key of array that have pid=8 .

I tried this code but it doesn't work:

$key = array_search($pid, $cart_e); // $cart_e is above array

For Example:

For deleting array with pid = 8 I want the result be like this after deleting:

Array ( [1] => Array ( [pid] => 11 [bv] => 0 [bs] => 0 ) [2] => Array ( [pid] => 10 [bv] => 0 [bs] => 0 ) )

as you see the whole array is deleted (I need this code), in some case I just deleted pid that result become like this(I don't want this):

Array ( [0] => Array ( [bv] => 0 [bs] => 0 ) [1] => Array ( [pid] => 11 [bv] => 0 [bs] => 0 ) [2] => Array ( [pid] => 10 [bv] => 0 [bs] => 0 ) )

so, How to find the array key of a pid with specific id?

Upvotes: 1

Views: 59

Answers (1)

user2575725
user2575725

Reputation:

How about creating a new copy of array using array_filter?

$array=array(array('pid'=>8,'bv'=>0,'bs'=>0),array('pid'=>11,'bv'=>0,'bs'=>0),array('pid'=>10,'bv'=>0,'bs'=>0));
$newArr = array_filter($array,function($arr){ /* `$arr` gets value of one nested array on each pass */
    return 8 !== $arr['pid'];
});

Or, just unset the unwanted nested array:

foreach($array as $key => $val){
    if(8 === $val['pid']){
        unset($array[$key]);
    }
}

Upvotes: 2

Related Questions