PHP多层嵌套数组遍历:如何提取酒店信息生成表格?
Got it, let's break this down step by step so it's totally clear. That nested array structure can feel overwhelming at first, but once you map out the layers, it's straightforward to traverse. Here's how to extract the hotelId, hotelName, and message fields into a table-friendly format:
First, Let's Map the Structure
Your JSON has two key layers of arrays:
- The top-level
hotelsarray: Each entry here is a full hotel object withhotelId,hotelName, and its ownhotelFiltersarray. - The
hotelFiltersarray inside each hotel: Each entry here has themessagevalue you need, tied to that specific hotel.
To get your table, you’ll need to loop through each hotel, then loop through each filter in that hotel, and pair the hotel’s details with the filter’s message.
Example Implementation (JavaScript)
Here’s a practical code snippet to process the data:
// Your original JSON data const hotelData = { "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" } ] } ] }; // Traverse the nested arrays to build table-ready data const tableRows = []; hotelData.hotels.forEach(hotel => { // Loop through each filter for the current hotel hotel.hotelFilters.forEach(filter => { tableRows.push({ hotelId: hotel.hotelId, hotelName: hotel.hotelName, message: filter.message // Uncomment below if you want to include filterName too // filterName: filter.filterName }); }); }); // Log the result (you can use this to render a table) console.log(tableRows);
Example Implementation (Python)
If you’re working in Python instead, here’s an equivalent snippet:
# Your original JSON data hotel_data = { "errorMessage": None, "hotels": [ { "hotelId": 1177, "hotelName": "Marriott", "hotelFilters": [{"filterName": "pool", "message": "yes"}] }, { "hotelId": 1542, "hotelName": "Hilton", "hotelFilters": [ {"filterName": "pool", "message": "no"}, {"filterName": "spa", "message": "yes"} ] } ] } # Build table-ready data table_rows = [] for hotel in hotel_data["hotels"]: for filter_item in hotel["hotelFilters"]: table_rows.append({ "hotelId": hotel["hotelId"], "hotelName": hotel["hotelName"], "message": filter_item["message"] }) # Print or use the data to generate a table print(table_rows)
Final Table Output
Once you run the code above, you’ll get a dataset that can be rendered into this table:
| hotelId | hotelName | message |
|---|---|---|
| 1177 | Marriott | yes |
| 1542 | Hilton | no |
| 1542 | Hilton | yes |
Notice that Hilton has two rows—one for each filter entry. This makes sense because each message is tied to a specific filter for the hotel, so we’re pairing each hotel detail with its corresponding filter message.
内容的提问来源于stack exchange,提问作者Melissa Bonsted

