我想用php创建多个json字符串数组。 Json必须像这样
[{
app:[{"id":"3","image_title":"Fashion","image_url":"6968ec4b67315f81bbf3b893ca02a195.jpg"}],
app2:[{"id":"3","image_title":"Fashion","image_url":"6968ec4b67315f81bbf3b893ca02a195.jpg"},
{"id":"3","image_title":"Fashion","image_url":"6968ec4b67315f81bbf3b893ca02a195.jpg"},
{"id":"3","image_title":"Fashion","image_url":"6968ec4b67315f81bbf3b893ca02a195.jpg"}]
}]
当我使用时
$array = array(
array( "ad1"=>
array("id"=>"3", "image_title"=>"Fashion", "image_url"=> "6968ec4b67315f81bbf3b893ca02a195.jpg")
),
array( "ad2"=>
array("id"=>"4", "image_title"=>"Fashion", "image_url"=> "6968ec4b67315f81bbf3b893ca02a195.jpg"),
array("id"=>"5", "image_title"=>"Fashion", "image_url"=> "6968ec4b67315f81bbf3b893ca02a195.jpg"),
array("id"=>"6", "image_title"=>"Fashion", "image_url"=> "6968ec4b67315f81bbf3b893ca02a195.jpg")
)
);
echo json_encode($array);
我得到的结果是
[{"ad1":{"id":"3","image_title":"Fashion","image_url":"6968ec4b67315f81bbf3b893ca02a195.jpg"}},
{"ad2":{"id":"4","image_title":"Fashion","image_url":"6968ec4b67315f81bbf3b893ca02a195.jpg"},
"0":{"id":"5","image_title":"Fashion","image_url":"6968ec4b67315f81bbf3b893ca02a195.jpg"},
"1":{"id":"6","image_title":"Fashion","image_url":"6968ec4b67315f81bbf3b893ca02a195.jpg"}}]
在id 5和6中显示0和1。
如何纠正? 请帮帮我?
答案 0 :(得分:0)
你的数组应该是这样的:
$array = [
[
'app' => [
'id' => 3, 'image_title' => 'Fashion', // and do so on
],
'app2' => [
['id' => 3, 'image_title' => 'Fashion',], // and do so on
['id' => 3, 'image_title' => 'Fashion',], // and do so on
['id' => 3, 'image_title' => 'Fashion',], // and do so on
],
]
];
echo json_encode($array);
然后输出应该与你描述的类似:
[{
app:[{"id":"3","image_title":"Fashion","image_url":"6968ec4b67315f81bbf3b893ca02a195.jpg"}],
app2:[{"id":"3","image_title":"Fashion","image_url":"6968ec4b67315f81bbf3b893ca02a195.jpg"},
{"id":"3","image_title":"Fashion","image_url":"6968ec4b67315f81bbf3b893ca02a195.jpg"},
{"id":"3","image_title":"Fashion","image_url":"6968ec4b67315f81bbf3b893ca02a195.jpg"}]
}]
它可能有点不同,例如,键被封装在双引号中,而整数(实际上是整数,而不是包含数字的字符串)将没有双引号。双引号和其他特殊字符可以在JSON字符串中进行转义(\"
)。
希望它有所帮助。