Home > database >  Looping through Curl response with php and pulling information out
Looping through Curl response with php and pulling information out

Time:01-19

I'm very new to coding and am studying CURL responses. My task is to loop through the results and list the "ORGANISATION_NAME" only.

My effort is this, but clearly fails and I'm not sure why.

Can someone guide me on how to do this with a simple explanation please?

foreach ($response[] as $key => $value) {
  echo $value['ORGANISATION_NAME'];
}

And this is the data.

[
  {
    "ORGANISATION_ID": 59931111,
    "ORGANISATION_NAME": "Low Level Repository"
  },      {
    "ORGANISATION_ID": 59931112,
    "ORGANISATION_NAME": "The Bike Shed"
  },      {
    "ORGANISATION_ID": 59931113,
    "ORGANISATION_NAME": "Taxi's are us"
  },      {
    "ORGANISATION_ID": 59931114,
    "ORGANISATION_NAME": "The apple tree"
  }
]

CodePudding user response:

Ok for starters that response looks like JSON, So you need to decode it.

Also I'm not quite sure whats going on with your foreach loop, try this:

foreach(json_decode($response) as $item){

echo $item->ORGANISATION_ID; // Returns the value for the object
echo $item->ORGANISATION_NAME;

}

If you are not ready for objects you can return and associative array using json decode by setting the second parameter to true:

foreach(json_decode($array, true) as $item){

echo $item['ORGANISATION_ID'];
echo $item['ORGANISATION_NAME'];

}

Json_decode();

if you plan on sending PHP arrays or Objects to JSON: json_encode();

PHP Arrays

  •  Tags:  
  • Related