从API返回数组提取机构ID:关联数组取值异常求助
Hey there! I see the problem you're running into—let's break this down and fix it quickly.
The Root Cause
When you use json_decode($result) without extra parameters, PHP returns stdClass objects by default, not associative arrays. That's why trying to access values like you would with an array (using $decodeArray['key']) throws an error—you're treating an object like an array!
Looking at your var_dump output, the structure is clearly nested objects with an array in the establishments field.
Solution 1: Use Associative Arrays Instead
If you prefer working with arrays, just pass true as the second argument to json_decode. This tells PHP to convert the JSON into associative arrays instead of objects:
// Decode into associative array $decodeArray = json_decode($result, true); // Now you can access the ID using array syntax $establishmentId = $decodeArray['establishments'][0]['establishment']['id']; echo $establishmentId; // Outputs: 0b246874-2c53-11e8-8fb6-001a4aa8ea16
Solution 2: Stick with Object Syntax
If you don't mind working with objects, you can use the -> operator to traverse the nested structure correctly:
// Keep the default object output $decodeArray = json_decode($result); // Access the ID using object property syntax $establishmentId = $decodeArray->establishments[0]->establishment->id; echo $establishmentId; // Outputs: 0b246874-2c53-11e8-8fb6-001a4aa8ea16
Pro Tip for Safety
To avoid errors if the API response structure ever changes (like missing fields), you can add checks with isset() before accessing values:
// For associative arrays if (isset($decodeArray['establishments'][0]['establishment']['id'])) { $establishmentId = $decodeArray['establishments'][0]['establishment']['id']; } // For objects if (isset($decodeArray->establishments[0]->establishment->id)) { $establishmentId = $decodeArray->establishments[0]->establishment->id; }
内容的提问来源于stack exchange,提问作者JeroenM

