我之前已经问过这个问题
Create Json in PHP using database
已经回答并且有效,但是需求有所改变,我试图获得的新输出无法通过此脚本实现。
这个脚本给我输出
{
"channelsCategories":
[
{
"name":"Movie",
"contents":
[
{
"name":"Channel 1",
"image":"Thanks.jpg",
},
{
"name":"Channel 2",
"image":"Thanks.jpg",
},
{
"name":"Channel 4",
"image":"amazon-logo...",
},
{
"name":"High",
"image":"Thanks.jpg",
}
]
},
{
"name":"Documentary",
"contents":
[
{
"name":"Channel 7",
"image":"amazon.....",
}
]
}
]
}
新要求是在类别数组和下方添加图像字段。
{
"channelsCategories":
[
{
"name":"Movie",
"image": "MoviePoster",
"contents":
[
{
"name":"Channel 1",
"image":"Thanks.jpg",
},
{
"name":"Channel 2",
"image":"Thanks.jpg",
},
{
"name":"Channel 4",
"image":"amazon-logo...",
},
{
"name":"High",
"image":"Thanks.jpg",
}
]
},
{
"name":"Documentary",
"image": "MoviePoster",
"contents":
[
{
"name":"Channel 7",
"image":"amazon.....",
}
]
}
]
}
到目前为止,我已经实现了这个数组结果,我想循环并得到上面的输出。
array(8) {
["Movieposter"]=> string(7) "Movieposter"
["News"]=> array(2) {
[0]=> array(5) {
["name"]=> string(8) "Dunya tv"
["url"]=> string(4) "http"
["image"]=> string(4) "http"
["type"]=> string(1) "3"
["status"]=> string(6) "Enable"
}
[1]=> array(5) {
["name"]=> string(6) "Geo tv"
["url"]=> string(4) "http"
["image"]=> string(4) "http"
["type"]=> string(1) "3"
["status"]=> string(6) "Enable"
}
}
["Dramaimg"]=> string(8) "Dramaimg"
["Drama"]=> array(2) {
[0]=> array(5) {
["name"]=> string(7) "drama 1"
["url"]=> string(4) "http"
["image"]=> string(4) "http"
["type"]=> string(1) "3"
["status"]=> string(6) "Enable"
}
[1]=> array(5) {
["name"]=> string(7) "drama 2"
["url"]=> string(4) "http"
["image"]=> string(4) "http"
["type"]=> string(1) "4"
["status"]=> string(6) "Enable"
}
}
["entertainmentimg"]=> string(16) "entertainmentimg"
["Entertainment"]=> array(1) {
[0]=> array(5) {
["name"]=> string(8) "indian 1"
["url"]=> string(4) "http"
["image"]=> string(4) "http"
["type"]=> string(1) "3"
["status"]=> string(6) "Enable"
}
}
["Pakistanimg"]=> string(11) "Pakistanimg"
["Pakistan"]=> array(1) {
[0]=> array(5) {
["name"]=> string(8) "pcontent"
["url"]=> string(8) "pcontent"
["image"]=> string(4) "http"
["type"]=> string(1) "7"
["status"]=> string(6) "Enable"
}
}
}
任何帮助指南都将不胜感激。
答案 0 :(得分:0)
这是为我工作的脚本.....
$typeArr = array();
foreach($result as $a){
$typeArr[$a['chanct_image']] = $a['chanct_image'];
$typeArr[$a['chanct_name']][] = array(
'name'=>$a['con_name'],
'url'=>$a['con_url'],
'image'=>$a['con_image'],
'type'=>$a['con_type'],
'status'=>$a['con_status']
);
}
$jsonarray = array();
foreach($typeArr as $type=>$contents){
if(is_array($contents) == FALSE){
$image = $type;
}
if(is_array($contents))
{
$jsonarray['channelsCategories'][] = array(
'name'=>$type,
'image'=>$image,
'contents'=>$contents
);
}
}
在第一个循环中添加了图像字段,然后在第二个循环中检查天气数组值是数组还是字符串,并基于填充第二个jsonarray。