我有一个post调用,它以两种方式之一返回JSON:
$json1 = '{"found":1,"email":"email1@domain.com","error":"","rd":"email2@domain.com"}'; $json2 = '{"found":1,"email":"email1@domain.com,email2@domain.com","error":"","rd":"email3@domain.com,email4@domain.com"}';
在第一个,email
和rd
参数每个只有一个电子邮件地址.在第二个中,这两个相同的参数每个都有多个收件人.
我需要从每个参数中获取电子邮件并将其添加到已存在的数组中:
$recipients = array('support@domain.com');
我可以$json1
使用以下代码使用变量:
array_push($recipients, $obj->{'rd'}, $obj->{'email'});
第二个JSON选项很少发布,但我仍然需要相同的代码才能适用于这两个实例.目前,如果我使用上面的代码与第二个JSON数据,它返回:
Array ( [0] => support@sculpturehospitality.com [1] => email3@domain.com,email4@domain.com [2] => email1@domain.com,email2@domain.com )
其中有多个电子邮件在同一个参数中.有没有人对我如何分离每个数组项中的电子邮件有任何见解?
一个工作的例子:
http://sandbox.onlinephpfunctions.com/code/24c4a1eaea98566b65cd36e221dd1f185e820ea6
只需explode()
用逗号表示你的属性并将它们添加到数组中,例如
$recipients = array_merge($recipients, explode(",", $obj->rd) , explode(",", $obj->email) /*, ... */);
还要注意,我现在使用array_merge()
而不是array_push()
,因为你不再有一个值,而是一个包含新元素的数组:
array_push():
//Single value $array = ["First element"]; $singleValue = "Second element"; array_push($array, $singleValue);
输出:
Array( [0] => First element [1] => Second element)
//Array $array = ["First element"]; $secondArray= ["Second element", "And third element"]; array_push($array, $secondArray);
输出:
Array( [0] => First element [1] => Array( [0] => Second element [1] => And third element))
array_merge():
//Single value $array = ["First element"]; $singleValue = "Second element"; $array = array_merge($array, $singleValue);
输出:
警告:array_merge():参数#2不是数组
//Array $array = ["First element"]; $secondArray= ["Second element", "And third element"]; $array = array_merge($array, $secondArray);
输出:
Array( [0] => First element [1] => Second element [2] => And third element)