dongtingxiao4697 2016-10-11 19:44
浏览 57
已采纳

搜索多维数组并返回特定值

Hard to phrase my question, but here goes. I've got a string like so: "13,4,3|65,1,1|27,3,2". The first value of each sub group (ex. 13,4,3) is an id from a row in a database table, and the other numbers are values I use to do other things.

Thanks to "Always Sunny" on here, I'm able to convert it to a multi-dimensional array using this code:

$data = '13,4,3|65,1,1|27,3,2';

$return_2d_array = array_map (
  function ($_) {return explode (',', $_);},
  explode ('|', $data)
);

I'm able to return any value using

echo $return_2d_array[1][0];

But what I need to be able to do now is search all the first values of the array and find a specific one and return one of the other value in i'ts group. For example, I need to find "27" as a first value, then output it's 2nd value in a variable (3).

  • 写回答

2条回答 默认 最新

  • dqkyz02602 2016-10-11 19:51
    关注

    Run one more foreach loop like this:

    $value_to_search = 27;
    foreach($return_2d_array as $array){ 
        if($array[0] == $value_to_search){ 
            echo $array[1];  // will give 3
            break; 
        } 
    }
    

    Here's the live demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算