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

如何使用PHP访问多维数组中的status键并输出对应值?

错误原因

原代码直接尝试访问最外层数组的status键,但该键实际嵌套在每一个外层数组元素的response[0]层级下,路径不匹配导致读取失败。

正确实现代码

<?php
// 先修正数组定义的语法问题(原写法缺少引号、语法不规范)
$array = array(
    0 => array(
        'error' => 'none',
        'response' => array(
            0 => array(
                'status' => 'success'
            )
        )
    ),
    1 => array(
        'error' => 'failed',
        'response' => array(
            0 => array(
                'status' => 'failed'
            )
        )
    )
);

// 方法1:直接遍历输出
foreach ($array as $item) {
    $status = $item['response'][0]['status'];
    echo 'status: ' . $status . ', ';
}

// 方法2:优化输出格式,去掉末尾多余的逗号
$statusArr = [];
foreach ($array as $item) {
    $statusArr[] = 'status: ' . $item['response'][0]['status'];
}
echo implode(', ', $statusArr);

最终输出

status: success, status: failed

内容的提问来源于stack exchange,提问作者Efoskhi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 11:54:03