dongyan3562 2014-02-19 19:06
浏览 34
已采纳

PHP搜索具有多个结果的多维数组?

I found a way to search my multidimensional array and output the result and it works, however it only finds the first match and stops. If I have more than one match in the array I want to be able to show them all.

My array looks like this (the first layer of keys goes from 0, 1, 2 etc):

Array
(
    [0] => Array
        (
            [mydevice] => blahblah
            [ipadd] => 10.10.10.209
            [portnum] => 16040
        )

function searcharray($value, $key, $array) {
   foreach ($array as $k => $val) {
       if ($val[$key] == $value) {
           return $k;
       }
   }
   return null;
}

$myoutput = searcharray($ptn2, mydevice, $newresult);

I can then echo the results using something like $newresult[$myoutput][mydevice].

However if I have more than one entry in the array with a matching data in the 'mydevice' key it doesn't return them (just the first one).

  • 写回答

2条回答 默认 最新

  • dourao1968 2014-02-19 19:09
    关注

    That is because return breaks the function. You could use something like this:

    function searcharray($value, $key, $array) {
        $result = array();    
        foreach ($array as $k => $val) {
            if ($val[$key] == $value) {
                $result[] = $k;
            }
        }
        return $result;
    }
    

    Now you will always get an array as result - empty if nothing was found. You can work with this like this e.g.

    $mydevicekeys = searcharray($ptn2, "mydevice", $newresult);
    foreach ($mydevicekeys as $mydevicekey) {
        // work with $newresult[ $mydevicekey ]["mydevice"]
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题