PHP将具有相同键的两个数组合并并输出为特定的json格式

时间:2019-05-27 06:56:57

标签: php arrays multidimensional-array

我的数据库有两个表。一种是调用图书信息,另一种是调用图像信息。我想将这两个表数据合并为一个JSON。如果img id与数据id匹配,则图像属于此书。我试图使用foreach将书数据循环到数组中,并使用另一个foreach循环书数据数组中的图像数据,但是未能获得预期的结果。

Book Table JSON:

{
 "data": [
    {
        "id": 17,
        "author": "Belcurls",
        "bookname": "You Never Know"
    },
    {
        "id": 18,
        "author": "Carolina",
        "bookname": "A Story Teller"
    },
    {
        "id": 19,
        "author": "Lokas",
        "bookname": "The Love"
    }
 ]
}

图像表JSON:

{
"img": [
    {
        "id": 18,
        "url": "image18.png"
    },
    {
        "id": 18,
        "url": "image18b.png"
    },
    {
        "id": 19,
        "url": "image19.png"
    },
    {
        "id": 19,
        "url": "image19b.png"
    },
    {
        "id": 19,
        "url": "image19c.png"
    }
]
}

预期结果:

{
 "data": [
    {
        "id": 17,
        "author": "Belcurls",
        "bookname": "You Never Know"
    },
    {
        "id": 18,
        "author": "Carolina",
        "bookname": "A Story Teller",
        "image":[
           {
             "url":"image18"
           },
           {
             "url":"image18b"
           }
         ]
    },
    {
        "id": 19,
        "author": "Lokas",
        "bookname": "The Love",
        "image":[
           {
             "url":"image19"
           },
           {
             "url":"image19b"
           },
           {
             "url":"image19c"
           }
         ]
    }
 ]
 }

2 个答案:

答案 0 :(得分:3)

Demo Link

您可以执行此循环,请查看内联文档以获取说明

foreach ($arr['data'] as $key => &$value) { // & to update changes as its address
    foreach ($imgs['img'] as $key1 => $value1) {
        if($value['id'] == $value1['id']){ // checking if match id of parent with images
            $value['image'][] = ['url' => $value1['url']]; // then simply push
        }
    }
}

如果要将json转换为php数组,请使用

 json_decode($yourjson, true); // second parameter is for converting it to array else it will convert into object.

答案 1 :(得分:1)

如果使数据数组具有关联性,则只需循环图像数组并将其添加到数据中正确的子数组。

// This flattens the array and makes it associative
$data = array_column($data['data'], null, 'id');

foreach($img['img'] as $v){
    $data[$v['id']]['image'][] = ['url' => $v['url']];
}
// Add the 'data' again
$final['data'] = array_values($data);

var_dump($final);
echo json_encode($final);

https://3v4l.org/736lQ