0

I'd like to convert a complex array in a simple json object. I know how to convert an array into json (json_encode) but my problem is how I could convert my basic array into the following json structure.

Array structure :

Array

Json Output :

{
    "id": "1",
    "name": "Random Access Memories",
    "tracks": [
        {
            "id": 1,
            "name": "Get Lucky",
            "artists": [
                {
                    "id": 1,
                    "name": "Daft Punk"
                },
                {
                    "id": 2,
                    "name": "Pharrell Williams"
                }
            ]
        },
        {
            "id": 1,
            "name": "Touch",
            "artists": [
                {
                    "id": 1,
                    "name": "Daft Punk"
                }
            ]
        }
    ],
    "album_artists": [
        {
            "id": 1,
            "name": "Daft Punk"
        },
        {
            "id": 2,
            "name": "Pharrell Williams"
        }
    ]
}
5
  • 7
    That doesn't look like an array, it looks like an image. Commented May 20, 2013 at 15:57
  • php.net/manual/en/function.json-decode.php check this link.. it will help you! Commented May 20, 2013 at 16:00
  • stackoverflow.com/questions/4328515/… Commented May 20, 2013 at 16:00
  • It is an illustration of my array. I uploaded it to make it more visual... Commented May 20, 2013 at 16:02
  • Did my answer work for you? Commented May 23, 2013 at 19:07

1 Answer 1

1

This isn't particularly good practise, but I'd loop through the initial array, or image, as displayed in the OP, to get an array of tracks, and then create a separate array for the json using the album name and album id of the first element in the tracks providing that all albums and album ids are the same.

$tracks = array();
$albumArtists = array();
foreach ($yourArrayNotAsAnImage as $track) {
    $tracks[] = $track;
    $albumArtists[] = array("name" => $track['artist_name'], "id" => $track['artist_id']);
}

$daftP = array("name" => $tracks[0]['album'], "id" => $tracks[0]['album_id'], "tracks" => $tracks, "album_artists" => $albumArtists);

echo json_encode($daftP);
Sign up to request clarification or add additional context in comments.

Comments

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.