You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从API返回数组提取机构ID:关联数组取值异常求助

Fixing the Issue with Extracting Establishment ID from API Response

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:44:58