Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

loops

php

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!!

like image 635
Craig van Tonder Avatar asked Jul 30 '12 12:07

Craig van Tonder


People also ask

How to loop through a multidimensional array PHP?

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.

How do you use each loop in a multidimensional array?

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.

How do you find the specific value of a key in an array?

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.


1 Answers

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

Using the above.

like image 143
Gavin Avatar answered Oct 01 '22 03:10

Gavin