morne
morne

Reputation: 4189

Find and delete all elements of $key in multidimensional array

Im trying to search and delete multiple values in a multidimensional array. I have tried to kind of mix it with a multiDim Search. I pass the array &$haystack by reference.

This should probably go in a do while loop, but as it stands it will go in a endless loop.

But nothing happens

$b = array(0 => array("patient" => 123, "condition" => "abc"), 
           1 => array("patient" => 987, "condition" => "xyz"),
           2 => array("patient" => 123, "condition" => "zzz"));



function in_array_r($needle, &$haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
          unset($haystack["patient"]);            
          return true;
        }
    }

    return false;
}


echo in_array_r(123, $b) ? 'found' : 'not found';

Print_r($b);

Expected Result

Array
(
    [1] => Array
        (
            [patient] => 987
            [condition] => xyz
        )

)

Upvotes: 0

Views: 75

Answers (2)

Ido
Ido

Reputation: 2054

function in_array_r($needle, &$haystack, &$count = 0)
{
    foreach($haystack as $index => $data)
    {
        if(is_array($data))
        {
            foreach($data as $key => $value)
            {
                if(is_array($value))
                    in_array_r($needle, $value, $count);
                else
                {
                    if($value === $needle)
                    {
                        unset($haystack[$key]);
                        $count++;
                    }
                }
            }
        }
    }

    return $count > 0;
}

$count = 0;

123:

echo (in_array_r(123, $b, $count) ? "found (".$count ." times)" : "not found") . "\n";

Output:

found (2 times)

1123:

echo (in_array_r(1123, $b, $count) ? "found (".$count ." times)" : "not found") . "\n";

Output:

not found

Upvotes: 1

Joel Hinz
Joel Hinz

Reputation: 25384

You don't need to pass by reference since you're not trying to change a value in an array. But you're on the right track! Here's a working example:

$patients = array(0 => array("patient" => 123, "condition" => "abc"), 
           1 => array("patient" => 987, "condition" => "xyz"),
           2 => array("patient" => 123, "condition" => "zzz"));

function remove_patient($patients, $number) {
    foreach ($patients as $key => $patient) {
        if ($patient['patient'] == $number) {
            unset($patients[$key]);
        }
    }
    return $patients;
}

And the example results:

var_dump(remove_patient($patients, 123));

array(1) {
  [1]=>
  array(2) {
    ["patient"]=>
    int(987)
    ["condition"]=>
    string(3) "xyz"
  }
}

Upvotes: 1

Related Questions