gpt4 book ai didi

javascript - 合并 PHP 数组和嵌套关系

转载 作者:行者123 更新时间:2023-11-30 08:32:23 40 4
gpt4 key购买 nike

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

var_dump($位置)

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

var_dump($房间)

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

我需要将房间数组合并到位置数组中,将房间分组到它们适当的位置下,这样我就可以将以下语法输出到名为 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);

关于javascript - 合并 PHP 数组和嵌套关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35760411/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com