我有一个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"}';
在第一个,电子邮件和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
)
其中有多个电子邮件在同一个参数中.有没有人对我如何分离每个数组项中的电子邮件有任何见解?
一个工作的例子:
解决方法:
用逗号表示你的财产,然后将它们添加到数组中,例如
$recipients = array_merge($recipients, explode(",", $obj->rd)
, explode(",", $obj->email) /*, ... */);
还要注意,我现在使用array_merge()而不是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))
//Single value
$array = ["First element"];
$singleValue = "Second element";
$array = array_merge($array, $singleValue);
输出:
Warning: array_merge(): Argument #2 is not an array
//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)
标签:php,arrays
来源: https://codeday.me/bug/20190528/1168259.html