通过用子数组数据替换父元素来删除多维数组中的级别

问题描述 投票:0回答:1

我有一个多维数组。

{
    "id": "13",
    "name": "Example",
    "location_name": "NY",
    "phone": [
        {
            "number": "0617357707"
        }
    ],
    "facilities": {
        "data": [
            {
                "name": "AC"
            },
            {
                "name": "Wi-Fi"
            }
        ]
    }
}

我要解决的问题是“设施”。在设施内部,有一个数据对象。如何在不删除内容“数据”的情况下删除数据?

预期结果:

{
    "id": "13",
    "name": "Example",
    "location_name": "NY",
    "phone": [
        {
            "number": "0617357707"
        }
    ],
    "facilities": [
        {
            "name": "AC"
        },
        {
            "name": "Wi-Fi"
        }
    ]
}

我尝试过使用

array_walk
或展平,但效果不佳。

php arrays multidimensional-array
1个回答
3
投票

看起来你可以这样做:

$results->facilities = $results->facilities->data

工作示例:

<?php

$var = json_decode('{
    "id": "13",
    "name": "Example",
    "location_name": "NY",
    "phone": [
        { "number": "0617357707" }
    ],
    "facilities": {
        "data": [
            { "name": "AC" }, { "name": "Wi-Fi" }
        ]
    }
  }');
var_dump($var);

$var->facilities = $var->facilities->data;
var_dump($var);
© www.soinside.com 2019 - 2024. All rights reserved.