jamesTheProgrammer
jamesTheProgrammer

Reputation: 1777

Can I access item in array without additional loop?

I have a data structure like this:

    array (size=4)  
  'active' => 
    array (size=1)
     170 => 
    object(stdClass)[2847]
      public 'item' => string '170' (length=3)
  'complete' => 
    array (size=1)
     8 => 
      object(stdClass)[2849]
       public 'item' => string '8' (length=1)
  'dropped' => 
    array (size=1)
     10 => 
     object(stdClass)[2850]
       public 'item' => string '10' (length=2)
  'total' => 
    array (size=1)
     188 => 
     object(stdClass)[2851]
       public 'item' => string '188' (length=3)

I am using this loop to iterate the datastruct and access the value in item.

        foreach($ecounts as $key => $value){

        if($key == 'total'){
            foreach($value as $i){
                $te = $i->item; 
            }
        }elseif($key == 'active'){
            foreach($value as $i){
                $ae = $i->item; 
            }
        }elseif($key == 'dropped'){
            foreach($value as $i){
                $de = $i->item; 
            }
        }elseif($key == 'complete'){
            foreach($value as $i){
                $ce = $i->item; 
            }
        }
    }

I am sure there is a smarter way to access the item value. The additional foreach() loop inside each if statement seems overkill, but I could not find a better way to accomplish.

Thank you for insights.

Upvotes: 1

Views: 89

Answers (1)

J D
J D

Reputation: 1818

Maybe you can decide the name of the variable before you start the additional loops.

Like

    foreach($ecounts as $key => $value){

        $var = ($key == 'total' ? 'te' : $key == 'active' : 'ae' ? $key ==  'dropped' : 'de' ? $key == 'complete' : 'ce');

        foreach($value as $i){
            ${$var} = $i->item; 
        }
}

Read http://php.net/manual/en/language.variables.variable.php for more documentation.

Upvotes: 1

Related Questions