JSON对象中的嵌套数组PHP
问题描述:
我要实现的JSON对象的下列格式输出:JSON对象中的嵌套数组PHP
[
{
"id":1,
"title":"Test Title",
"url":"http://test.com/",
"images":[
{
"width":100,
"height":100,
"size":17000,
"url":"http://test.com",
"timestamp":14566698
},
{
"width":100,
"height":100,
"size":160000,
"url":"http://test.com",
"timestamp":1451903339
}
]
}
]
我从数据库中收集的所有数据,并将其保存到变量和使用PHP创建JSON对象也包括一个环路它需要创建多个属性:不过我实现输出是不是我的意图实现
for ($x = 1; $x <= 2; $x++) {
$JSONarray[] = array(
'id' => $x,
'title' => $title,
'url' => $url,
'images' => array(
'width' => $width,
'height' => $height,
'size' => $size,
'url' => urldecode($image),
'timestamp' => $timestamp
),
array(
'width' => $width2,
'height' => $height2,
'size' => $size2,
'url' => urldecode($image2),
'timestamp' => $timestamp2
)
);
}
echo json_encode($JSONarray, JSON_UNESCAPED_SLASHES);
。那我得到的输出是如下:
[
{
"id":1,
"title":"Test Title",
"url":"http://test.com/",
"images":{
"width":100,
"height":10,
"size":17000 ,
"url":"http://test.com/",
"timestamp":14566698
},
"0":{
"width":100,
"height":100,
"size":160000 ,
"url":"http://test.com/",
"timestamp":1451903339
}
}
]
答
注重图像阵列,它必须看起来像这样:
for ($x = 1; $x <= 2; $x++) {
$JSONarray[] = array(
'id' => $x,
'title' => $title,
'url' => $url,
'images' => array(
(object)array(
'width' => $width,
'height' => $height,
'size' => $size,
'url' => urldecode($image),
'timestamp' => $timestamp
),
(object)array(
'width' => $width2,
'height' => $height2,
'size' => $size2,
'url' => urldecode($image2),
'timestamp' => $timestamp2
)
)
);
}
答
我认为你需要这个......
for ($x = 1; $x <= 2; $x++) {
$JSONarray[] = array(
'id' => $x,
'title' => $title,
'url' => $url,
'images' => array(
array(
'width' => $width,
'height' => $height,
'size' => $size,
'url' => urldecode($image),
'timestamp' => $timestamp
),
array(
'width' => $width2,
'height' => $height2,
'size' => $size2,
'url' => urldecode($image2),
'timestamp' => $timestamp2
)
)
);
}
echo json_encode($JSONarray, JSON_UNESCAPED_SLASHES);
告诉我们你得到的输出是什么。我现在唯一能看到的就是你在'images'中缺少另一个数组,你需要''images'=> array(array(“。所以现在你可能在你的内部JSOnarray的索引0处得到秒图像数组 – muffe
'object'和'array'之间有区别,上面的JSON记法显示一个对象数组作为'images'元素的值,你试着将两个数组插入到这个元素中,这是a)不同的和b)将不起作用。尝试为图片创建对象,然后将_those_推入图片数组中。 – arkascha