我制作了这段代码:
$jsonpost = array();
while ($query_news->have_posts()) : $query_news->the_post();
$jsonpost[] = array("tags"=> array(
'name' => 'name',
'content' => ''
));
endwhile;
echo json_encode($jsonpost);
获取json feed。 这给出了以下结果
[
{
"tags": {
"name": "tes",
"content": "test"
}
},
{
"tags": {
"name": "test",
"content": "test"
}
}
]
但是我想要以下结果,使用额外的[],但我不知道如何添加它:
[
{
"tags": [{
"name": "tes",
"content": "test"
}]
},
{
"tags": [{
"name": "test",
"content": "test"
}]
}
]
我该怎么做?
答案 0 :(得分:2)
修改代码以包装array in an array。
$jsonpost[] = array("tags"=> array( array(
'name' => 'name',
'content' => ''
)));
echo json_encode($jsonpost);
答案 1 :(得分:1)
这应该有效(我没有测试过)。
$jsonpost = array();
while ($query_news->have_posts()) :
$query_news->the_post();
$row = []; //create empty array
$row[] = [ //add the assoc array to that array (this makes it numeric)
'name' => 'name',
'content' => ''
];
$jsonpost[] = [ "tags"=> $row];
endwhile;
echo json_encode($jsonpost);
阵列结构中的差异在数组结构中可见;
不正确:
Array
(
[0] => stdClass Object
(
[tags] => stdClass Object
(
[name] => tes
[content] => test
)
)
[1] => stdClass Object
(
[tags] => stdClass Object
(
[name] => test
[content] => test
)
)
)
Outpus: [{&#34;标记&#34; {&#34;名称&#34;:&#34; TES&#34;&#34;内容&#34;:&#34;测试&#34;}}, {&#34;标记&#34; {&#34;名称&#34;:&#34;测试&#34;&#34;内容&#34;:&#34;测试&#34;}}] < / p>
正确:
Array
(
[0] => stdClass Object
(
[tags] => Array
(
[0] => stdClass Object
(
[name] => tes
[content] => test
)
)
)
[1] => stdClass Object
(
[tags] => Array
(
[0] => stdClass Object
(
[name] => test
[content] => test
)
)
)
)
输出: [{&#34;标记&#34;:[{&#34;名称&#34;:&#34; TES&#34;&#34;内容&#34;:&#34;测试&#34;}] },{&#34;标记&#34;:[{&#34;名称&#34;:&#34;测试&#34;&#34;内容&#34;:&#34;测试&#34;} ]}]