合并 PHP 个数组和嵌套关系

Merging PHP arrays and nest relations

我在 PHP 中有两个数组需要传递给 JS 脚本。 PHP数组为locationsrooms如下:

var_dump($locations)

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

var_dump($rooms)

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

我需要将 rooms 数组合并到 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" }
         ] 
 }

作为学徒的一部分,我在这里和那里学习了一些东西,但我还不够好,无法独自解决这个问题哈哈抱歉,谢谢!

如果您创建一个按位置 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);

您可以使用 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 );

eval.in demo

我在您的一条评论中注意到您正在使用数据库,因此我决定继续并添加一个答案。另一种选择是通过在查询中加入位置和房间来避免以两个数组开头。我对 tables/columns 的名称做了一些假设,但像这样的查询应该有效:

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