简体   繁体   English

遍历数组PHP中的对象

[英]Iterate through objects in array PHP

My PHP is receiving data like this: 我的PHP正在接收这样的数据:

[
    {
      "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. 问题是foreach只运行一次,我可以成功处理第一个对象中的电子邮件地址。 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. 因此,在上述数据的情况下,我只会收到hello@example.com,而不会得到info@example.com。

How do I need to adjust my foreach ? 我该如何调整我的foreach

EDIT: Full code here following the janky way that Sendgrid requires you to send it. 编辑:这里的完整代码遵循Sendgrid要求您发送的方式。

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. 使用json_decode ,返回值是一个关联数组而不是对象。

Therefore, your code $value->EMAIL is invalid. 因此,您的代码$value->EMAIL无效。

Second 第二

The decoded JSON will become something like this: 解码后的JSON将变成这样:

 [ [ "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. 因此,在foreach ($entityBody as $value)$value指向数组而不是值。

Hence, $email = $value['EMAIL'] will fail too. 因此, $email = $value['EMAIL']也将失败。

Solution

Use double foreach : 使用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 您可以通过将其复制粘贴到PhpFiddle中来运行上面的代码

EDIT 编辑

Apparently json_decode returns object for {...} data format . 显然json_decode返回{...}数据格式的对象

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. 我认为使您的代码仅运行一次的原因是,在foreach的第二次迭代中,未找到$value->EMAIL值,因此引发错误并中断了执行。

Solution is to first check the data using isset() . 解决方案是首先使用isset()检查数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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