Expected JSON structure:
预期的JSON结构:
{"music" : [
{
"title" : "Jazz in Paris",
"album" : "Jazz & Blues"
},
{
"title" : "Jazz in Paris",
"album" : "Jazz & Blues"
}
.......
.......
]}
Current JSON:
{"music":{"title":"Origin of evil","album":"devotional"}}
Code:
$sub = array();
foreach ($this->data as $value)
{
$sub['title'] = $value['title'];
$sub['album'] = "devotional";
}
$audio = array('music'=>$sub);
echo json_encode($audio);
4 个解决方案
#1
1
Just create an array outside of the foreach
and then append the subarray
into main array using []
.
只需在foreach之外创建一个数组,然后使用[]将子数组附加到主数组中。
Like this,
$audio=array();
$audio["music"]=array();
foreach ($this->data as $value)
{
$sub = array();
$sub['title'] = $value['title'];
$sub['album'] = "devotional";
$audio["music"][]=$sub;
}
echo json_encode($audio);
This will create an array of music and each sub array as a object of it.
这将创建一个音乐数组,并将每个子数组作为其对象。
#2
0
Change a bit in your existing code-
改变现有代码中的一点 -
Just add extra array to the $sub
as array($sub)
.
只需将额外数组添加到$ sub as array($ sub)。
$audio = array('music'=>array($sub));
#3
0
Try with this
试试这个
$sub = array();
foreach ($this->data as $value)
{
$temp['title'] = $value['title'];
$temp['album'] = "devotional";
array_push($sub, $temp);
}
$audio = array('music'=>$sub);
echo json_encode($audio);
#4
0
You need to wrap things in another array. just change echo json_encode(array($audio));
你需要将东西包装在另一个数组中。只需更改echo json_encode(array($ audio));
$sub = array();
foreach ($this->data as $value)
{
$sub['title'] = $value['title'];
$sub['album'] = "devotional";
}
$audio = array('music'=>array($sub)); // just add array so whole things are wrap in another array.
echo json_encode($audio);
#1
1
Just create an array outside of the foreach
and then append the subarray
into main array using []
.
只需在foreach之外创建一个数组,然后使用[]将子数组附加到主数组中。
Like this,
$audio=array();
$audio["music"]=array();
foreach ($this->data as $value)
{
$sub = array();
$sub['title'] = $value['title'];
$sub['album'] = "devotional";
$audio["music"][]=$sub;
}
echo json_encode($audio);
This will create an array of music and each sub array as a object of it.
这将创建一个音乐数组,并将每个子数组作为其对象。
#2
0
Change a bit in your existing code-
改变现有代码中的一点 -
Just add extra array to the $sub
as array($sub)
.
只需将额外数组添加到$ sub as array($ sub)。
$audio = array('music'=>array($sub));
#3
0
Try with this
试试这个
$sub = array();
foreach ($this->data as $value)
{
$temp['title'] = $value['title'];
$temp['album'] = "devotional";
array_push($sub, $temp);
}
$audio = array('music'=>$sub);
echo json_encode($audio);
#4
0
You need to wrap things in another array. just change echo json_encode(array($audio));
你需要将东西包装在另一个数组中。只需更改echo json_encode(array($ audio));
$sub = array();
foreach ($this->data as $value)
{
$sub['title'] = $value['title'];
$sub['album'] = "devotional";
}
$audio = array('music'=>array($sub)); // just add array so whole things are wrap in another array.
echo json_encode($audio);