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!!
You can simply use the foreach loop in combination with the for loop to access and retrieve all the keys, elements or values inside a multidimensional array in PHP.
In the foreach loop, the $element variable will contain the value of the current array item for every iteration. The loop continues till the last element in the array. In the case of the two-dimensional array, we can use the foreach loop to access the first nested array in the first iteration and so on.
The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.
foreach( $orderItems as $key => $obj)
{
echo $key;
echo $obj['quantity'];
echo $obj['total'];
}
Using the above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With