递归array_search

3zz*_*zzy 8 php arrays search

我有一个多维数组:

$categories = array(
    array(
        'CategoryID' => 14308,
        'CategoryLevel' => 1,
        'CategoryName' => 'Alcohol & Food',
        'CategoryParentID' => 14308
    ),
    // CHILD CATEGORIES
    array(
        array(
            'CategoryID' => 179836,
            'CategoryLevel' => 2,
            'CategoryName' => 'Alcohol & Alcohol Mixes',
            'CategoryParentID' => 14308
        ),
        array(
            array(
                'CategoryID' => 172528,
                'CategoryLevel' => 2,
                'CategoryName' => 'Antipasto, Savoury',
                'CategoryParentID' => 14308
            )
        )
    )
);
Run Code Online (Sandbox Code Playgroud)

我需要获取索引的确切位置,因为array_search不能在多维数组上工作,我正在使用PHP手册页上提供的一个函数.

function recursive_array_search($needle,$haystack) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
            return $current_key;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

..但它也只返回第一个数组的键:

echo recursive_array_search(172528, $categories); // outputs 1
Run Code Online (Sandbox Code Playgroud)

我期待着:

[1][1][0]
Run Code Online (Sandbox Code Playgroud)

Pie*_*per 11

您可以像这样更改递归函数,它应该为您提供解决方案:

function recursive_array_search($needle, $haystack, $currentKey = '') {
    foreach($haystack as $key=>$value) {
        if (is_array($value)) {
            $nextKey = recursive_array_search($needle,$value, $currentKey . '[' . $key . ']');
            if ($nextKey) {
                return $nextKey;
            }
        }
        else if($value==$needle) {
            return is_numeric($key) ? $currentKey . '[' .$key . ']' : $currentKey . '["' .$key . '"]';
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

这将导致

[1][1][0]["CategoryID"]
Run Code Online (Sandbox Code Playgroud)

由于CategoryID也是多维数组中的键.

如果你不想这样,你可以调整功能

function recursive_array_search($needle, $haystack, $currentKey = '') {
    foreach($haystack as $key=>$value) {
        if (is_array($value)) {
            $nextKey = recursive_array_search($needle,$value, $currentKey . '[' . $key . ']');
            if ($nextKey) {
                return $nextKey;
            }
        }
        else if($value==$needle) {
            return is_numeric($key) ? $currentKey . '[' .$key . ']' : $currentKey;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢堆,这是有效的.很抱歉这个愚蠢的问题,但是如果我想打印那个读取索引的值,我就不能用`$ categories.$ key`打印,它只打印类别,然后字面打印字符串. (2认同)