简体   繁体   中英

PHP - 2D Arrays - Looping through array keys and retrieving their values?

I have an array that outputs like this:

1 => 
array
  'quantity' => string '2' (length=1)
  'total' => string '187.90' (length=6)

2 => 
array
  'quantity' => string '2' (length=1)
  'total' => string '2,349.90' (length=8)

I would like to loop through each array keys and retrieve the set of 3 values relating to them, something like this (which doesnt work):

foreach( $orderItems as $obj=>$quantity=>$total)
{
    echo $obj;
    echo $quantity;
    echo $total;
}

Would someone be able to give some advice on how I would accomplish this, or even a better way for me to be going about this task. Any information relating to this, including links to tutorials that may cover this, would be greatly appreciated. Thanks!!

foreach( $orderItems as $key => $obj)
{
    echo $key;
    echo $obj['quantity'];
    echo $obj['total'];
}

Using the above.

You need to read the docs on forEach() a little more, since your syntax and understanding of it is somewhat incorrect.

$arr = array(
    array('foo' => 'bar', 'foo2', 'bar2'),
    array('foo' => 'bar', 'foo2', 'bar2'),
);
foreach($arr as $sub_array) {
    echo $sub_array['foo'];
    echo $sub_array['bar'];
}

forEach() iteratively passes each key of the array to a variable - in the above case, $sub_array (a suitable name, since your array contains sub-arrays). So within the loop body, it's that you need to interrogate.

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