很多层嵌套在php中

时间:2018-01-03 13:00:31

标签: php arrays nested

{
    "errorMessage": null,
    "hotels": [{
        "hotelId": 1177,
        "hotelName": "Marriott",
        "hotelFilters": [{
            "filterName": "pool",
            "message": "yes"
        }]
    }, {
        "hotelId": 1542,
        "hotelName": "Hilton",
        "hotelFilters": [{
            "filterName": "pool",
            "message": "no"
        }, {
            "filterName": "spa",
            "message": "yes"
        }]
    }

如何遍历数组以获取包含hotelID,酒店名称和消息的表格?我迷失在阵列的水平。

1 个答案:

答案 0 :(得分:1)

以此为第一种方法;)

 /**                                    
 * Transforms JSON Hotel data to PHP array
 * 
 * @param $data The data as JSON String
 * @return array|bool
 */
public function transformHotelDataFromJson($data)
{
    $_data = json_decode($data);
    if (array_key_exists('hotels', $_data) === false) {
        return false;
    }
    $myData = [];
    foreach ($_data['hotels'] as $hotel) {
        $myData[] = [
            'id' => $hotel['hotelId'],
            'name' => $hotel['hotelName'],
            'message' => $hotel['hotelFilters']['message'],
        ];
    }
    return $myData;
}