如何在多维数组中找到键?

时间:2019-05-29 09:17:14

标签: php arrays multidimensional-array

我有一个多维数组,我需要创建一个searchCategory($ categories,$ id)函数,该函数必须返回'title'属性的值。

尝试此代码,它仅适用于多维数组的一层。

多维数组:

$categories = array(    array(
    "id" => 1,
    "title" =>  "Обувь",
    'children' => array(
        array(
            'id' => 2,
            'title' => 'Ботинки',
            'children' => array(
                array('id' => 3, 'title' => 'Кожа'),
                array('id' => 4, 'title' => 'Текстиль'),
            ),
        ),
        array('id' => 5, 'title' => 'Кроссовки',),
    )),     array(
    "id" => 6,
    "title" =>  "Спорт",
    'children' => array(
        array(
            'id' => 7,
            'title' => 'Мячи'
        )
    )   ), );

我尝试解决问题的代码:

function searchCategory($categories, $id) {

    foreach($categories as $category) {

        if($category['id'] == $id) {

            echo $category['title'] . '<br>';

        }
    } 
};

我需要我的函数在所有数组中查找id值,并在找到数组的情况下返回标题

2 个答案:

答案 0 :(得分:2)

这是递归迭代器案例,请查看内联文档以获取解释

function searchCategory($categories, $id)
{
    $arrayiter = new RecursiveArrayIterator($categories);
    $iteriter  = new RecursiveIteratorIterator($arrayiter);
    foreach ($iteriter as $key => $value) {
        // checking if iterator comes to point where key is id and value matched
        if ($key == 'id' && $value == $id) {
            // returning matched value with current iterator instance
            return $iteriter->getInnerIterator()['title'];
        }
    }
    return '';
}
echo searchCategory($categories, 2).'<br/>';
echo searchCategory($categories, 7);

Working demo

RecursiveArrayIterator-此迭代器允许以与ArrayIterator相同的方式遍历数组和对象的同时取消设置和修改值和键。另外,可以迭代当前的迭代器条目。
RecursiveIteratorIterator-可用于通过递归迭代器进行迭代。
RecursiveIteratorIterator::getInnerIterator:获取内部迭代器

答案 1 :(得分:0)

您需要递归创建函数

演示:https://3v4l.org/CR7CD

function searchCategory($categories, $id) {
    foreach($categories as $category) {
        if($category['id'] == $id)
            echo $category['title'] . '<br>';
        if(isset($category['children']))
            searchCategory($category['children'],$id);
    } 
}