1

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.

jamesTheProgrammer
  • 1,747
  • 4
  • 22
  • 34
  • Sub array always have single element so only `item`? – Bora Sep 12 '13 at 14:36
  • 1
    It seems a bit unnecesary to use the inside foreach loop. You set each of these values `$te $ae $de $ce` several times, and they get the last value from each array. Is that what you wanted? – Kelu Thatsall Sep 12 '13 at 14:36
  • Another question, is your data structure like this and you cannot change it? Can there be more elements in each of these 1-element arrays? – Kelu Thatsall Sep 12 '13 at 14:38
  • http://stackoverflow.com/questions/1921421/get-first-element-of-an-array – Kelu Thatsall Sep 12 '13 at 14:42

1 Answers1

1

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.

J D
  • 1,768
  • 2
  • 18
  • 20
  • 1
    I'm not sure if this is the best way to do it, because I am still doing a conditional (ternary). – J D Sep 12 '13 at 15:00