【问题标题】:PHP search_array for multi dimension array多维数组的PHP搜索数组
【发布时间】:2015-11-05 00:11:47
【问题描述】:

如何获取数组的子数组的索引如下所示:

Array
(
    [1000] => Array
        (
            [firstName] => Ori
            [lastName] => Smith
            [children] => Array
                (
                    [0] => 1001
                    [1] => 1002
                    [2] => 1003
                    [3] => 1004
                    [4] => 1005
                    [5] => 1006
                    [6] => 1007
                    [7] => 1008
                    [8] => 1009
                    [9] => 1010
                )
        )
)

所以如果我给 1009 作为搜索,它应该返回 1000。

它不适用于此代码:

array_search($childrenId, array_column(myArray, 'children'));

【问题讨论】:

  • 我可以告诉你为什么这不起作用。 array_column 会在您的示例中的数组中为您提供一个数组,因此您的 array_search 甚至不会找到您正在寻找的子 ID。此外,即使您确实找到了正确的子数组,我认为 array_column 也会返回一个从零开始的数组

标签: php arrays search


【解决方案1】:

试试这个

$result = array(
    '1000'=>array('children'=>array('1001','1002')),
    '2000'=>array('children'=>array('2001','2002'))
);
$searchValue = 2001;
$keyName = '';

foreach ($result as $key => $row) {
    foreach ($row['children'] as $child) {
        if ($child == $searchValue) {
            $keyName = $key;
            break;
        }
    }
}

echo $keyName;

【讨论】:

    【解决方案2】:

    你可以使用这个功能找到here:

    function getParentStack($child, $stack) {
    foreach ($stack as $k => $v) {
        if (is_array($v)) {
            // If the current element of the array is an array, recurse it and capture the return
            $return = getParentStack($child, $v);
    
            // If the return is an array, stack it and return it
            if (is_array($return)) {
                return array($k => $return);
            }
        } else {
            // Since we are not on an array, compare directly
            if ($v == $child) {
                // And if we match, stack it and return it
                return array($k => $child);
            }
        }
    }
    
    // Return false since there was nothing found
    return false;
    }
    

    我猜你可以通过key(getParentStack(1009, $myarr))获取密钥或者修改函数。

    【讨论】:

      猜你喜欢
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 2013-09-20
      相关资源
      最近更新 更多