Search code examples
phparraysjsonforeachfeed

PHP foreach loop without the as?


I'm retrieving data from a json feed like this:

{
  'data': {

   'stuffs': [
     {
       'cats': '12',
       'dogs': '53',
       'bananas': '8',
     },
     {
       'cats': '42',
       'dogs': '49',
       'bananas': '18',

     },
     {
       'cats': '14',
       'dogs': '900',
       'bananas': '2',
     }]

  }
}

And grabbing the data with a function like this:

function getData($url){

     $json = file_get_contents($url);                                      
     $json_output = json_decode($json, TRUE);

       foreach ($url['data']['stuffs'] as $benum){

         $cats = $benum['cats'];
         $dogs = $benum['dogs'];
         $bananas = $benum['bananas'];

       }



    $myarray = array(

    "cat" => $cats,
    "dog" => $dogs,
    "banana" => $bananas,

    );

  return $myarray;

}

I want to set up a foreach loop something like this:

   foreach ($myarray as $data){

   echo $data['cat'];
   echo $data['dog'];
   echo $data['banana'];

   }

And have it return something like this :

 12
 53
 8

 42
 49
 18

 14
 900
 2

But foreach($myarray as $data) is not working.

The problem is that it only returns 1 character from each key in the array which seems to be random.

Is there something that I could do that would be like not having "as" in the foreach at all?

Like:

  foreach($myarray){

      // the goods    

  }

Thanks in advance.


Solution

  • function getData($url){
    
         $myarray = array();
    
         $json = file_get_contents($url);                                      
         $json_output = json_decode($json, TRUE);
    
           foreach ($url['data']['stuffs'] as $benum){
    
             $cats = $benum['cats'];
             $dogs = $benum['dogs'];
             $bananas = $benum['bananas'];
    
             $myarray[] = array(
    
                "cat" => $cats,
               "dog" => $dogs,
                "banana" => $bananas,
    
                );
    
           }
    
    }
    
     foreach ($myarray as $data){
    
       echo $data['cat'];
       echo $data['dog'];
       echo $data['banana'];
    
       }
    

    You should get the result in the way you want. You will always need the "as" with foreach.