【问题标题】:Converting complex array structure into json将复杂的数组结构转换为json
【发布时间】:2013-05-15 05:46:54
【问题描述】:

我想将一个复杂的数组转换为一个简单的 json 对象。我知道如何将数组转换为 json (json_encode),但我的问题是如何将我的基本数组转换为以下 json 结构。

数组结构:

Json 输出:

{
    "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"
        }
    ]
}

【问题讨论】:

标签: php arrays json


【解决方案1】:

这不是特别好的做法,但我会遍历 OP 中显示的初始数组或图像,以获取曲目数组,然后使用专辑名称为 json 创建一个单独的数组和曲目中第一个元素的专辑 ID,前提是所有专辑和专辑 ID 都相同。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2021-12-18
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    相关资源
    最近更新 更多