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

    }
}
3
  • Why do you want to use RecursiveIterator for this task, when it can be solved pretty straight-forward with simple foreach loop? Commented Apr 2, 2014 at 4: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 Commented Apr 2, 2014 at 4: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 for a very detailed explanation of how this SPL feature can be useful. Commented Apr 2, 2014 at 4:48

3 Answers 3

1

you can try this.

foreach($cars as $key=>$value){
  echo $value['Name']." has a price of ".$value['Price'];
}
Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

0

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

$keys = array_keys($array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.