json 合并PHP数组和嵌套关系

mzaanser  于 2023-02-26  发布在  PHP
关注(0)|答案(3)|浏览(121)

我在PHP中有两个数组需要传递给JS脚本,PHP数组是locationsrooms,如下所示:

变量转储($个位置)

Array ( [0] => Array 
               ( [id] => 1
                 [name] => "London"  )
        [1] => Array 
               ( [id] => 2
                 [name] => "Manchester"  )
      )

变量转储($个房间)

Array ( [0] => Array 
               ( [id] => 1
                 [locationId] => "1"
                 [name] => "Lon Room 1"  )
        [1] => Array 
               ( [id] => 2
                 [locationId] => "1"
                 [name] => "Lon Room 2"  )
        [2] => Array 
               ( [id] => 3
                 [locationId] => "1"
                 [name] => "Lon Room 3"  )
        [3] => Array 
               ( [id] => 4
                 [locationId] => "2"
                 [name] => "Man Room 1"  )
        [4] => Array 
               ( [id] => 5
                 [locationId] => "2"
                 [name] => "Man Room 2"  )
      )

我需要将房间数组合并到locations数组中,将房间分组到适当的位置下,这样我就可以向名为DailyPlot Scheduler的JS插件输出以下语法。

{ name: "London", id: "1", children:[
         { name : "Lon Room 1", id : "1" },
         { name : "Lon Room 2", id : "2" },
         { name : "Lon Room 3", id : "3" }
         ] 
 },
 { name: "Manchester", id: "2", children:[
         { name : "Man Room 1", id : "1" },
         { name : "Man Room 2", id : "2" }
         ] 
 }

我在这里和那里学习一些东西,作为我学徒生涯的一部分,但还没有好到足以让我自己把我的头包起来,哈哈,对不起,谢谢!

5n0oy7gb

5n0oy7gb1#

如果创建一个按位置id索引的数组,则可以使用索引为指定位置添加子项:

$locations_by_id = [];

foreach($locations as $location) {
    $location['children'] = []; //initialize children to an empty array
    $locations_by_id[$location['id']] = $location;
}

foreach($rooms as $room) {    
    //add room to location
    $locations_by_id[$room['locationId']]['children'][] = $room;
}

$locations = array_values($locations_by_id); //removes the id index

print json_encode($locations);
2j4z5cfb

2j4z5cfb2#

我注意到在你的一条评论中你正在使用一个数据库,所以我决定继续添加一个答案。另一个选择是通过在查询中连接位置和房间来避免一开始就有两个数组。我对表/列的名称做了一些假设,但是这样的查询应该可以工作:

SELECT l.id AS l_id, l.name AS l_name, r.id AS r_id, r.name AS r_name
FROM locations l LEFT JOIN rooms r ON l.id = r.locationId
ORDER BY l.id, r.id

然后,在从结果中提取行时,可以使用位置ID作为键来构造数组。

while ($room = $query->fetch()) { // fetch method depends on what db extension you're using
    $rooms[$room['l_id']]['name'] = $room['l_name'];
    $rooms[$room['l_id']]['id'] = $room['l_id'];
    $rooms[$room['l_id']]['children'][] = array('name' => $room['r_name'], 
                                                'id'   => $room['r_id']);
}

echo json_encode(array_values($rooms));
shyt4zoc

shyt4zoc3#

您可以使用locations数组的所有id创建一个数组,然后使用array_search将每个rooms数组直接添加到locations数组:

$index = array_column( $locations, 'id' );
foreach( $rooms as $key => $val )
{
    $found = array_search( $val['locationId'], $index );
    $locations[$found]['children'][] = array( 'name' => $val['name'], 'id' => $val['id'] );
}

$json = json_encode( $locations );
    • 一个

相关问题