Blessan Kurien Blessan Kurien - 1 month ago 9
JSON Question

generate associative array json from php

Expected JSON structure:

{"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);

Answer

Just create an array outside of the foreach and then append the subarray into main array using [].

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.