Reputation: 1491
I'm a bit confused. I have the following array: I am trying to use the STL iterator to loop through it and return sum all the values of any array where Name = Dodge. I noticed I cannot do $cars['Price']
as I could with a for each loop. How do I get the price of the car?
$cars = Array {
array[0] {
'Name' => 'Dodge',
'Drive' => '4W',
'Price' => '15,000'
},
array[1] {
'Name' => 'Corolla',
'Drive' => '2W',
'Price' => '17,300'
}
..
}
Is this correct:
try {
$iter = new RecursiveArrayIterator($cars);
// loop through the array
$all_totals = array();
foreach(new RecursiveIteratorIterator($iter) as $key => $value)
{
if($key == 'Name' && $value == 'Dodge')
{
//how to get the Price of the car?
//push into totals array:
$all_totals[$value] = $value;
}
}
}
Upvotes: 2
Views: 1681
Reputation: 10111
Use [array_keys()][1]
for this.
$keys = array_keys($array);
Upvotes: 0
Reputation: 199
Use this code for perticular Dodge car price.
$sumofDodgeCar = 0;
foreach($cars as $value){
if($value['Name']=='Dodge') {
echo $value['Name']." has a price of ".$value['Price'];
$sumofDodgeCar = $sumofDodgeCar + $value['Price'];
}
}
echo "All Dodge car Price Sum :".$sumofDodgeCar;
Upvotes: 1
Reputation: 1402
you can try this.
foreach($cars as $key=>$value){
echo $value['Name']." has a price of ".$value['Price'];
}
Upvotes: 1