douwan7382 2018-01-03 13:00
浏览 59

很多层嵌套在php中

{
    "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"
        }]
    }

How do I traverse the array to get a table with hotelID, hotel Name and message? I'm lost in the levels of the array.

  • 写回答

1条回答 默认 最新

  • doushitang4276 2018-01-03 13:10
    关注

    Take this as a first approach ;)

     /**                                    
     * 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;
    }
    
    评论

报告相同问题?