简体   繁体   English

查找和删除多维数组中$ key的所有元素

[英]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. 我试图将其与multiDim搜索混合。 I pass the array &$haystack by reference. 我通过引用传递了数组&$haystack

This should probably go in a do while loop, but as it stands it will go in a endless loop. 这可能应该在do while循环中进行,但就目前而言,它将是一个无限循环。

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

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

Output: 输出:

found (2 times)

1123 : 1123

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

Output: 输出:

not found

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM