简体   繁体   中英

Properly extracting an embedded array from another array

I am trying to extract an array embedded in another array using the standard foreach loop, the problem is it keep returning unwanted data.

Array

Array
(
    [id] => 2035443879
    [status] => Unshipped
    [sku] => 0340024275-UsedGood
    [isbn] => 0340024275
    [condition] => Used
    [number_of_items] => 1
    [title] => Linnets and Valerians (Knight Books)
    [purchase_date] => 1361536149
    [0] => Array
        (
            [status] => Shipped
            [title] => Linnets and Valerians (Knight Books)
            [date] => 1361491200
        )
 )

Print function

function mapStatus($orders){
    foreach($orders as $order){
        echo "<pre>";
        print_r($order);
        echo "</pre>";

        foreach(array_unique($order) as $item){
            echo "-".$item["status"]."-";
        }


    }
}

Outcome

-2--U--0--0--U--1--W--L--H--1--Shipped-

As you can see from my outcome what was printed is not exactly what I expected, it seems that I am printing the first character of every index in the array and not just the actual array I want.

I'm aware that I can use a is_array() function to determine if what I am printing is coming from an array object but I would like to know if there is proper way to do what I want?

for ($i = 0; $i < $order['number_of_items']; $i++) {
  echo "-".$order[$i]["status"]."-";
}

However, I recommend a different data structure. Instead of having the items as indexed elements within the order array, you should have $order['items'] , which points to an array. Then you can use:

foreach ($order['items'] as $item)

Then you don't need $order['number_of_items'] , you can just use count($order['items']) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM