简体   繁体   中英

Iterate through objects in array PHP

My PHP is receiving data like this:

[
    {
      "EMAIL": "hello@example.com",
      "GENDER": "Male"
    },
    {
      "EMAIL": "info@example.com",
      "GENDER": "Male"
    }
  ]

So, I then do something like this:

$entityBody=json_decode($data); //$data like the array above

foreach($entityBody as $value){
$email = $value->EMAIL;
//do something with $email

The problem is that the foreach only runs once and I can successfully process the email address in the first object. But the rest are ignored. So, in the case of the data above, I just get hello@example.com and nothing for info@example.com.

How do I need to adjust my foreach ?

EDIT: Full code here following the janky way that Sendgrid requires you to send it.

foreach($entityBody as $value){
$array[0]['email'] = $value->EMAIL;

$data_json = json_encode($array);
$curl = curl_init();
$headers = array();
$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = "Authorization: Bearer XXXX";

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.sendgrid.com/v3/contactdb/recipients",

  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
   CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => $headers,
  CURLOPT_POSTFIELDS => $data_json,
));

$response = curl_exec($curl);
$err = curl_error($curl);
if ($err) {

die();
}
else{//run good stuff
$new = json_decode( $response, true );
if($new['persisted_recipients'][0]!=""){

$submit = $new['persisted_recipients'][0];

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.sendgrid.com/v3/contactdb/lists/".$listId."/"."recipients/".$submit,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
   CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => $headers,

));

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
  echo "cURL Error #:" . $err;

die();
}
else{

 echo("success");
die();
}

}  
}
}

First

When using json_decode , the returned value is an associative array instead of an object.

Therefore, your code $value->EMAIL is invalid.

Second

The decoded JSON will become something like this:

 [ [ "EMAIL" => "hello@example.com", "GENDER" => "Male" ], [ "EMAIL" => "info@example.com", "GENDER" => "Male" ] ] 

Therefore, in foreach ($entityBody as $value) , the $value points to an array instead of a value.

Hence, $email = $value['EMAIL'] will fail too.

Solution

Use double foreach :

 $data = '[ { "EMAIL": "hello@example.com", "GENDER": "Male" }, { "EMAIL": "info@example.com", "GENDER": "Male" } ]'; $entityBody = json_decode($data); foreach ($entityBody as $value){ // Remember $value === array foreach ($value as $key => $val){ // You can process your data here if ($key === 'EMAIL') echo "Email: {$val}<br>"; else if ($key === 'GENDER') echo "Gender: {$val}<br>"; } } 

You can run the above code by copy-pasting it in PhpFiddle

EDIT

Apparently json_decode returns object for {...} data format .

So you can use the following code:

 foreach ($entityBody as $value){ $email = isset($value->EMAIL) ? $value->EMAIL : false; $gender = isset($value->GENDER) ? $value->GENDER : false; } 

Which makes your code perfectly fine.

I think what makes your code only run once is that, in the 2nd iteration of foreach , the value $value->EMAIL is not found, therefore throwing error and break out of execution.

Solution is to first check the data using isset() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM