Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use foreach when there is no array in the object?
    text
    copied!<p>I was using this successfully, so I thought:</p> <pre><code>foreach ($trip-&gt;STOPS-&gt;STOP as $key=&gt;$value) { </code></pre> <p>Most of the time the data looks like this:</p> <pre><code> ["STOPS"]=&gt; object(stdClass)#247 (1) { ["STOP"]=&gt; array(4) { [0]=&gt; object(stdClass)#248 (2) { ["NAME"]=&gt; string(11) "Short Hills" ["TIME"]=&gt; string(20) "7/30/2013 6:38:24 AM" } [1]=&gt; object(stdClass)#249 (2) { ["NAME"]=&gt; string(8) "Millburn" ["TIME"]=&gt; string(20) "7/30/2013 6:41:24 AM" } [2]=&gt; object(stdClass)#250 (2) { ["NAME"]=&gt; string(19) "Newark Broad Street" ["TIME"]=&gt; string(20) "7/30/2013 6:53:00 AM" } [3]=&gt; object(stdClass)#251 (2) { ["NAME"]=&gt; string(21) "New York Penn Station" ["TIME"]=&gt; string(20) "7/30/2013 7:13:00 AM" } } } } </code></pre> <p>However the above PHP code caused a problem when STOP didn't contain an array of elements, when it looked like this:</p> <pre><code> ["STOPS"]=&gt; object(stdClass)#286 (1) { ["STOP"]=&gt; object(stdClass)#287 (2) { ["NAME"]=&gt; string(21) "New York Penn Station" ["TIME"]=&gt; string(20) "7/30/2013 8:13:00 AM" } } } </code></pre> <p>So as you might guess, the instead of it making $key=>$value to be the array element and the array of the NAME/TIME, it was making $key to be NAME or TIME, which is wrong of course.</p> <p>How can I use this foreach method properly without having to check to see if foreach $trip->STOPS->STOP contains an array or more than one element?</p> <p>The source of this data is from a SOAP request which is returned as JSON.</p> <p>Or is my approach here totally wrong? If so, please kindly enlighten me? Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload