2

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;
        }

    }
}
brokenfoot
  • 11,083
  • 10
  • 59
  • 80
Undermine2k
  • 1,481
  • 4
  • 28
  • 52
  • Why do you want to use `RecursiveIterator` for this task, when it can be solved pretty straight-forward with simple `foreach` loop? – raina77ow Apr 02 '14 at 04:41
  • @raina77ow I know it can I was trying to learn the RecursiveIterator class. Also from what I've read the SPL is faster for large arrays – Undermine2k Apr 02 '14 at 04:44
  • 1
    See, you won't learn how to wield a screwdriver when you only have nails to deal with. ) RecursiveIterator is most suitable when you have to process complex hierarchies - trees, in particular. Check [this thread](http://stackoverflow.com/questions/12077177/how-does-recursiveiteratoriterator-work-in-php) for a very detailed explanation of how this SPL feature can be useful. – raina77ow Apr 02 '14 at 04:48

3 Answers3

1

you can try this.

foreach($cars as $key=>$value){
  echo $value['Name']." has a price of ".$value['Price'];
}
Viswanath Polaki
  • 1,357
  • 1
  • 10
  • 19
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;
user2706194
  • 199
  • 8
0

Use [array_keys()][1] for this.

$keys = array_keys($array);
Farzad
  • 842
  • 2
  • 9
  • 26
SagarPPanchal
  • 9,839
  • 6
  • 34
  • 62