简体   繁体   English

如何检查多维数组在所有“级别”上是否都包含某些键和值对?

[英]How to check if the multidimensional array contains certain key and value pair on all “levels”?

I have this multi-dimensional array: 我有这个多维数组:

$arr = array(
    array(
        array(
            'page_id'    => '75',
            'book_color' => 'red',
            'book_name'  => 'Bible - patch nr. 593',
        ),
    ),
    array(
        array(
            array(
                'page_id'    => '85',
                'book_color' => 'blue',
                'book_name'  => 'Bible',
            ),
            array(
                'page_id'    => '84',
                'book_color' => 'black',
                'book_name'  => 'Bible - extended version',
            ),
            array(
                'page_id'    => '83',
                'book_color' => 'green',
                'book_name'  => 'Bible - for children and Americans',
            ),
        ),
        array(
            'page_id'    => '68',
            'book_color' => 'green',
            'book_name'  => 'Bible - Quran mashup',
        ),

    ),
    array(
        'page_id'    => '96',
        'book_color' => 'yellow',
        'book_name'  => 'Bible - patch nr. 594',
    ),
);

And I need to check if this array contains this key => value pair: 而且我需要检查此数组是否包含此键=>值对:

'book_name' => 'Bible'

So, as you can see, it can by in the first subarray or the second or even inside of more nested arrays. 因此,如您所见,它可以在第一个子数组中,也可以在第二个甚至更多嵌套数组中。

How to make a check that can return true or false depending if there is found, no matter on what level, this keyand value pair. 如何进行检查,以返回是否为true或false,这取决于是否找到此键值对。

You can use array_walk_recursive over here like as 您可以在这里像这样使用array_walk_recursive

$book_name = [];

array_walk_recursive($arr, function($v, $k)use(&$book_name) {
    if ($k == 'book_name') {
        $book_name[$v] = (strpos($v,"Bible") !== false) ? "Found" : "God not found";
    }
});
print_r($book_name);

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM