Laravel中遍历打印API解析JSON数据?解决非对象属性报错
Let's break down what's going wrong here and fix it step by step.
1. The Core Issue in Your Loop
Your current code is trying to loop over a single hotel object ($results->GeoSearchRS->GeoSearchResults->GeoSearchResult[$i]) instead of the entire array of results. When you increment $i, you eventually hit an index that doesn't exist—this is exactly what causes the "Trying to get property 'Name' of non-object" error, because GeoSearchResult[$i] stops being a valid object at that point.
2. Fixed Loop Code
Assuming GeoSearchResult is an array of hotel objects (which it should be for multiple results), you need to loop directly over that array. We'll also add safety checks to handle edge cases:
$response = sabreApiCall($url, $data_array); $results = json_decode($response); // First, validate the response structure to avoid unexpected errors if (isset($results->GeoSearchRS->GeoSearchResults->GeoSearchResult) && is_array($results->GeoSearchRS->GeoSearchResults->GeoSearchResult)) { foreach ($results->GeoSearchRS->GeoSearchResults->GeoSearchResult as $hotel) { // Check if the Name property exists before accessing it if (isset($hotel->Name)) { echo $hotel->Name . "<br>"; // Add line break for readability } else { echo "Hotel name not available<br>"; } } } else { echo "No hotel results found or invalid API response structure"; }
3. Key Improvements Explained
- Removed manual
$icounter:foreachautomatically iterates over every element in theGeoSearchResultarray—you don't need to track an index manually. - Added structure validation: We first confirm that
GeoSearchResultexists and is an array. This prevents errors if the API returns an empty result or a different data structure than expected. - Checked for the
Nameproperty: Even if a hotel object exists, it might not have aNamefield (e.g., incomplete data). Adding this check avoids another round of "undefined property" errors.
4. Debug Tip: Inspect the Full Response
If you're still confused about the data structure, print the full decoded response to see exactly what you're working with:
echo "<pre>"; print_r($results); echo "</pre>";
This will show you if GeoSearchResult is an array, a single object (for cases where there's only one result), or something else. If it's a single object sometimes, you can adjust the code to handle both scenarios:
$geoResults = $results->GeoSearchRS->GeoSearchResults->GeoSearchResult; // Convert single object to array if needed to keep the loop consistent $hotels = is_array($geoResults) ? $geoResults : [$geoResults]; foreach ($hotels as $hotel) { if (isset($hotel->Name)) { echo $hotel->Name . "<br>"; } }
内容的提问来源于stack exchange,提问作者Shahid Hussain

