Question : Trouble Accessing Values in Multidimensional Array

I have an array ($array). When I do a print_r on the array, I get the code posted below (truncated for readability)

I need to go through the array to search for the arrays that have the key "weight" and get its value.

I was trying to use a foreach loop but keep getting an error. What am I doing wrong?
The error I get is "Undefined offset: 0", then 1, then 2 and so on through the foreach loop.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
// print_r($array)
Array ( 
  [0] => Array ( [accountid] => AH0001 [account] => Company1 [weight] => 22 ) 
  [1] => Array ( [accountid] => AH0002 [account] => Company2 [weight] => ) 
  [2] => Array ( [accountid] => AH0003 [account] => Company3 [weight] => ) 
  [3] => Array ( [accountid] => AH0004 [account] => Company4 [weight] => 9 )
)

// The foreach loop
foreach($array as $key => $value)
{
  echo $value[$key]["weight"];
}

Answer : Trouble Accessing Values in Multidimensional Array

Within your loop, $value is an array and the keys are accountid, account, and weight, so you would only need the following:

echo $value['weight'];


Random Solutions  
 
programming4us programming4us