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 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line