loop through subArray as $key => $value in PHP

2019-07-27 02:02发布

问题:

given this data structure:

    array(2) {
    [0] array(7) {
        ["model_id"] 218
        ["total"] 10
        ["brand"] "This Brand"
        ["model_name"] "This Name"
        ["picture"] "this pic.jpg"
        ["color"] "Black"
        ["sizes"] array(3) {
            ["4"] "10 %"
            ["5"] "80 %"
            ["6"] "10 %"
        }
    }
    [1] array(7) {
        ["model_id"] 219
        ["total"] 10
        ["brand"] "This Brand"
        ["model_name"] "ThatName"
        ["picture"] "that pic.jpg"
        ["color"] "Black"
        ["sizes"] array(3) {
            ["4"] "20 %"
            ["5"] "50 %"
            ["6"] "30 %"
        }
    }
}

How can you loop into sizes as $key => $value ?

What I tried didn't work so far, like nested loops.

foreach($array as $i){

            foreach($i as $z){

                foreach($z as $key => $value){

                    print_r($key);

                }  
            }
        }
    }

results in error: Invalid argument supplied for foreach()

回答1:

foreach($array as $i){
    foreach($i['sizes'] as $key => $value){
        echo $key.'->'.$value;
    }       
}


回答2:

$arrayas = json_decode($array);
foreach($arrayas $i){

        foreach($i as $z){

            foreach($z as $key => $value){

                print_r($key);

            }  
        }
    }
}

try this one



回答3:

Please try this

$decarray = json_decode($array);

foreach($decarray as $keyDec => $valArr ){
    foreach($valArr as $keyOuter => $valOuter){
        if($keyOuter == "sizes"){
            foreach($valOuter as $keyInner => $valInner){
                echo $keyInner.":".$valInner ''
            }  
        }
    }
}