dongluoqiu0255 2015-05-09 21:02
浏览 225
已采纳

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

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
        )

)
  • 写回答

2条回答 默认 最新

  • doutuoji8418 2015-05-09 21:13
    关注

    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"
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现