Find and remove all elements of $ key in a multidimensional array

advertisements

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
        )

)


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"
  }
}