Patwan
9 months ago

Using a For loop on a PHP multi-dimensional array

Posted 9 months ago by Patwan

Working on a multidimensional array in PHP (From an API) which is 4 levels deep. Am trying to use a for loop to separate/dissect the nested arrays so that they may exist as independent entities so that I may use them in the blade. e.g agency_sales , unit_sales, agents

When I use it in a foreach loop in the view I only get 1 array out of the possible 4 arrays....

They are stored in a variable called rsm

"regional_sales": [
    {
        "id": "75875",
        "agency_sales": [
            {
                "id": "157",
                "unit_sales": [
                    {
                        "id": "777",
                        "agents": [
                            {
                                "agent_no": "75939",
                                "policies": [
                                    "IL*********"
                                ]
                            },
                            {
                                "agent_no": "75939",
                                "policies": [
                                    "IL**********"
                                ]
                            }
                        ]
                    },
                    {
                        "id": "111",
                        "agents": [
                            {
                                "agent_no": "758",
                                "policies": [
                                    "IL2*********"
                                ]
                            },
                            {
                                "agent_no": "75939",
                                "policies": [
                                    "IL20**********"
                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

For loop am using

for($a=0; $a < count($rsm); $a++){
    $asm = $rsm[$a]['agency_sales'];
    //dd($asm);
    for($b = 0; $b < count($asm); $b++){
        $usm = $asm[$b]['unit_sales'];
        for($c = 0; $c < count($usm); $c++){
            $ag = $usm[$c]['agents'];
            //dd($ag);
        }   
    }
}

When I use it in a foreach loop I get only one array among the 4 arrays

 @foreach($usm as $u)
    <a href="#SubMenu1" class="list-group-item" data-toggle="collapse" data-parent="#SubMenu1"> USM ID : {{ $u['id'] }} <i class="fa fa-caret-down"></i></a>
 @endforeach

Please sign in or create an account to participate in this conversation.