Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP unpack array

Tags:

arrays

php

I would like to learn a smart way to unpack nested array. For instance, i have an array variable $rma_data['status'] which looks like below;

 [status] => Array
    (
        [0] => Array
            (
                [created] => 1233062304107
                [statusId] => 5
                [statusName] => Open
            )

        [1] => Array
            (
                [created] => 1233061910603
                [statusId] => 2
                [statusName] => New
            )

        [2] => Array
            (
                [created] => 1233061910603
                [statusId] => 1
                [statusName] => Created
            )

    )

I would like to store the Created timestamps and statusId into an variables based on the condition like: if we find out there is "Open" status exist, we will use Open instead of "New" and "Created" . If there is only New and Created, we will use New instead .

Current version of my way to do that:

for($i=0; $i<count($rma_data['status']); $i++)
                {
                    switch($rma_data['status'][$i]['statusId'])
                    {
                        case 5: 

                                            case 2:

                                            case 3:
                }

Any ideas?

like image 958
QLiu Avatar asked Oct 21 '22 17:10

QLiu


1 Answers

For small to medium scale, what you already have looks good.

My only suggestions would be to use additional variables, for example the count and to unroll some of the compact code to be more efficient and readable.

For example:

$total=count($rma_data['status']);
for($i=0; $i<$total; $i++){
    $x=$rma_data['status'][$i];
    if($x['statusName']=='Open'){ // Use your criteria
        $t=$x['created'];
        //...Do Work
    }
}
like image 67
zaf Avatar answered Oct 27 '22 10:10

zaf