1

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);
2
  • 1
    You need to wrap whole array in another array. Commented Oct 15, 2016 at 8:51
  • for the associative structure of the music part of array you need to add extra array here, the example given by the alokPatel as answer. Commented Oct 15, 2016 at 8:54

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, glad to help.
0

Change a bit in your existing code-

Just add extra array to the $sub as array($sub).

$audio = array('music'=>array($sub));

Comments

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

Comments

0

You need to wrap things in another array. just change 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 Comment

@FrayneKonok. oh yeah brother it was my mistake thanks for point it out :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.