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.

4
  • Sub array always have single element so only item? Commented Sep 12, 2013 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? Commented Sep 12, 2013 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? Commented Sep 12, 2013 at 14:38
  • stackoverflow.com/questions/1921421/… Commented Sep 12, 2013 at 14:42

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm not sure if this is the best way to do it, because I am still doing a conditional (ternary).

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.