递归数组_搜索 [英] Recursive array_search

查看:29
本文介绍了递归数组_搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组:

$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
            )
        )
    )
);

我需要获取索引的确切位置,并且由于 array_search 不适用于多维数组,因此我使用的是 PHP 手册页上提供的函数之一.

I need to get the exact location of the index, and since array_search doesn't work on multi-dimensional arrays, I'm using one of the functions provided on the PHP manual page.

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;
}

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

.. but it also returns the key of the first array only:

echo recursive_array_search(172528, $categories); // outputs 1

我期待:

[1][1][0]

推荐答案

你可以像这样改变你的递归函数,这应该会给你解决方案:

You can change your recursive function like this, which should give you the solution:

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;
}

这将导致

[1][1][0]["CategoryID"]

因为 CategoryID 也是多维数组中的一个键.

Since CategoryID is also a key in your multidimensional array.

如果你不想要这个,你可以将函数调整为

If you don't want this, you can adapt the function to

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;
}

这篇关于递归数组_搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆