我有一个 JSON 文件,其结构如下所示(非常简单):
[
{
"customerId": "M12345",
"houses": [
{
"id": "OBJ12345_1731321200",
"status": {
"id": "4",
"name": "Sold"
},
{
"id": "OBJ12345_1732393235",
"status": {
"id": "4",
"name": "Såld"
}
],
"plots": [
{
"id": "OBJ12345_1771637082",
"status": {
"id": "4",
"name": "Sold"
}
],
"projects": [],
"farms": [],
"commercialPropertys": [],
"condominiums": [],
"foreignProperties": [],
"premises": []
}
]
我这样做是为了获取所有对象的数组,但不知道如何保留键“房屋”或“地 block ”?
// Create array of all objects
$AllEstatesList = array();
foreach ($GetEstateList[0] as $GetEstateType) {
foreach ($GetEstateType as $GetEstate) {
if ($GetEstate["id"] != null) {
$AllEstatesList[] = $GetEstate;
}
}
}
我需要弄清楚如何创建一个数组来保留来自父项的键并将它们包含在新数组中...
我要找的结果是这样的:
Array
(
[0] => Array
(
[type] => houses
[id] => OBJ12345_1731321200
[status] => Array
(
[id] => 4
[name] => Såld
)
)
[1] => Array
(
[type] => houses
[id] => OBJ12345_1732393235
[status] => Array
(
[id] => 4
[name] => Såld
)
)
[2] => Array
(
[type] => plots
[id] => OBJ15053_1771637082
[status] => Array
(
[id] => 4
[name] => Såld
)
)
)
请帮忙! :)
最佳答案
你想在创建第一个foreach时保留每个数组对象的key 环形。语法如下所示:
foreach ($arr as $key => $value) {
echo "{$key} => {$value} ";
print_r($arr);
}
所以对于你的例子,它会是这样的:
// Create array of all objects
$AllEstatesList = array();
foreach ($GetEstateList[0] as $EstateType => $GetEstateType) {
foreach ($GetEstateType as $GetEstate) {
if ($GetEstate["id"] != null) {
$GetEstate["type"] = $EstateType;
$AllEstatesList[] = $GetEstate;
}
}
}
关于PHP foreach 数组 - 保留键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64579773/