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

谁说胖子不能爱 提交于 2020-01-16 01:53:31

问题


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 ''
            }  
        }
    }
}


来源:https://stackoverflow.com/questions/36353541/loop-through-subarray-as-key-value-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!