我有两个JSON字符串,如下所示:
$json1 = '[ {"src":"1","order":"2"}, {"src":"10","order":"20"}, ... ]';
和
$json2 = '[ {"src":"4","order":"5"}, {"src":"6","order":"7"}, ... ]';
我正试图用这个来合并它们:
$images = array_merge(json_decode($json1 ),json_decode($json2));
$json = '[';
$comma = null;
foreach($images as $image)
{
$comma = ',';
$json .= $comma.'{"src":"'.$image['src'].'","order":"'.$image['order'].'"}';
}
$json .= ']';
echo $json;
但我得到了这个错误:
错误:不能使用stdCLASS的对象类型。。
我做错了什么?
当您调用json_decode时,您将其解码为一个对象。如果你想让它成为一个数组,你必须进行
$images = array_merge(json_decode($json1, true), json_decode($json2, true));
有关json_decode的详细信息:
http://php.net/manual/en/function.json-decode.php
当您制作时
foreach($images as $image)
{
$comma = ',';
$json .= $comma.'{"src":"'.$image['src'].'","order":"'.$image['order'].'"}';
}
您需要更改:
foreach($images as $image)
{
$json .= $comma.'{"src":"'.$image->src.'","order":"'.$image->order.'"}';
$comma = ',';
}
要访问对象的字段,您需要使用"->"运算符,如$image->src
此外,第一个$comma需要为null,因此我更改了foreach内的行顺序。
问题是您正在手动执行json_encode
应该执行的操作。本部分:
$images = array_merge(json_decode($json1), json_decode($json2));
很好。
array_merge
中的单个json_decode
将解码为对象数组,array_merge
将它们合并在一起。您不需要将它们解码为多维数组就可以实现这一点。
要将其返回到JSON中,您不应该使用foreach
循环并手动构建JSON。您得到的错误是,因为您使用数组语法访问对象,但您可以通过将foreach
循环替换为以下内容来避免整个问题:
$json = json_encode($images);
事实上,整件事可以用一行代码完成:
$json = json_encode(array_merge(json_decode($json1), json_decode($json2)));
如果您绝对想将其用作数组,只需将其设置为一个即可。这些对于在循环中设置对象属性非常有用,尤其是在类中。但不是你的案子。
$json1 = '[ {"src":"1","order":"2"}, {"src":"10","order":"20"}]';
$json2 = '[ {"src":"4","order":"5"}, {"src":"6","order":"7"}]';
$images = array_merge(json_decode($json1),json_decode($json2));
$json = '[';
$comma = null;
foreach($images as $image)
{
$image=(array)$image;
$comma = ',';
$json .= $comma.'{"src":"'.$image['src'].'","order":"'.$image['order'].'"}';
}
$json .= ']';