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

2019-07-27 02:07发布

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()

3条回答
老娘就宠你
2楼-- · 2019-07-27 02:27
$arrayas = json_decode($array);
foreach($arrayas $i){

        foreach($i as $z){

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

                print_r($key);

            }  
        }
    }
}

try this one

查看更多
你好瞎i
3楼-- · 2019-07-27 02:36

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 ''
            }  
        }
    }
}
查看更多
贪生不怕死
4楼-- · 2019-07-27 02:37
foreach($array as $i){
    foreach($i['sizes'] as $key => $value){
        echo $key.'->'.$value;
    }       
}
查看更多
登录 后发表回答