简体   繁体   中英

How to recursively loop through multidimensional array to get a key match

I have this variable and array. I want to loop through the array keys and if there is a match with $cat value I want to get the array key name which its belong to Architecture & Design . How can I do this? Thank you

$cat = 'sound';

Array
(
    [Architecture & Design] => Array
        (
            [0] => architecture
            [1] => fashion
            [2] => game
            [3] => graphic
            [4] => interior
            [5] => industrial
            [6] => textile
            [7] => web
            [8] => ui
            [9] => sound
        )

    [Test array] => Array
        (
            [0] => item1
            [1] => item2
            [2] => item3
            [3] => item4
            [4] => item5
            [5] => item6
            [6] => item7
            [7] => item8
            [8] => item9
            [9] => item0
        )

)

You can use next function with foreach loop:

$cat = 'sound';

function get_key($array,$cat){

    foreach($array as $key=>$subar){

        foreach($subar as $val){
            if ($val === $cat) return $key;  
        }  

    }
    return '';
}

echo get_key($data,$cat);

It will produce to you the first appearance.

Demo

Loop over your array with key value pair. If the key is Architecture & Design , skip it, else continue with other keys. If you find a value in them equal to $cat , print what the respective value is in Architecture & Design .

<?php 

$cat = 'item1';


foreach($array as $key => $value){
    if($key === 'Architecture & Design') continue;
    foreach($value as $index => $val){
        if($cat === $val){
            echo $val, " " , $array['Architecture & Design'][$index],PHP_EOL;
        }
    }
}

Use a foreach loop with key and value :

https://paiza.io/projects/J3hi4BM51b3-2jq2ayperw

foreach($arr["Architecture & Design"] as $key => $value){
    if($value === $cat){
        echo $key;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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