【问题标题】:How to get values from multidimensional array, searching by name?如何从多维数组中获取值,按名称搜索?
【发布时间】:2018-01-13 22:35:37
【问题描述】:

我想检查item2 的每个子数组作为第一个元素中的值(索引0)。 如果是这样,我想返回第二个元素的值(索引1)。

这是我的多维数组:

$arr = Array
(
    1 => Array
        (
            0 => 'item',
            1 => 3,
            2 => 20,
        ),

    2 => Array
        (
            0 => 'item2',
            1 => 1,
            2 => 21,
        ),

    7 => Array
        (
            0 => 'item3',
            1 => 4,
            2 => 26,
        ),

    20 => Array
        (
            0 => 'item4',
            1 => 1,
            2 => 39,
        ),

    22 => Array
        (
            0 => 'item1',
            1 => 10,
            2 => 39,
        ),
     23 => Array
        (
            0 => 'item2',
            1 => 11,
            2 => 39,
        )
);

预期结果是:[1,11]

我使用了这个函数,但它没有返回所有结果:

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))) {
            return true;
        }
    }

    return false;
}

【问题讨论】:

    标签: php arrays search multidimensional-array


    【解决方案1】:

    当然,使用不能有多个具有相同键的数组元素 (item2=>1,item2=>11) ,但可以收集所有值 [1] (1,11)

    例如

    $arr = // your array()
    $res = array();
    foreach ($arr as $row) {
        if (isset($row[0]) && $row[0] == 'item2') {
            $res[] = $row[1];
        }
    }
    
    var_dump($res);
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 2012-03-05
      • 2011-10-03
      • 1970-01-01
      • 2018-01-01
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多