我有点困惑。我有以下数组:我试图使用STL迭代器循环它并返回任何数组的所有值,其中Name = Dodge。我注意到我无法为每个循环执行$cars['Price']
。我如何得到汽车的价格?
$cars = Array {
array[0] {
'Name' => 'Dodge',
'Drive' => '4W',
'Price' => '15,000'
},
array[1] {
'Name' => 'Corolla',
'Drive' => '2W',
'Price' => '17,300'
}
..
}
这是否正确:
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;
}
}
}
答案 0 :(得分:1)
你可以试试这个。
foreach($cars as $key=>$value){
echo $value['Name']." has a price of ".$value['Price'];
}
答案 1 :(得分:1)
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;
答案 2 :(得分:0)
使用[array_keys()][1]
进行此操作。
$keys = array_keys($array);