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

使用StdClass重组JSON仍报错:Cannot use object of type stdClass as array

解决「Cannot use object of type stdClass as array」错误的方案

我来帮你定位问题根源——你遇到的这个错误和json_encode的参数无关(而且json_encode的第二个参数是JSON编码选项,true对应的是JSON_FORCE_OBJECT,和你误以为的「转数组」完全不是一回事,转数组是json_decode的参数功能),真正的问题是你混用了对象和数组的访问语法。

问题具体分析

你明确说明$fileArray是由stdClass对象组成的数组,也就是说$fileArray[$key](或者foreach里的$file变量)是一个stdClass对象,而非数组。但你代码里多处用了数组下标语法['sequence']来访问对象属性,比如:

// 错误写法:用数组下标访问对象属性
$tmpFileObject->name = $fileArray[$key]['sequence']->name;
$outObj->unknowns = $fileArray[$key]['sequence']->unknowns;

这种写法直接违反了PHP的语法规则,自然会抛出「不能把stdClass对象当数组用」的错误。

修正后的完整代码

我们只需要把所有数组下标访问['xxx']改成对象属性访问->xxx,同时优化foreach变量的使用(直接用$file更简洁),再去掉json_encode里不必要的true参数:

function getFilesJson($fileArray){ 
    $arrayOfStudentFiles = []; 
    foreach ($fileArray as $file){ 
        $outObj = new StdClass; 
        $tmpFileObject = new StdClass; 
        $outObj->files = []; 
        
        // 修正:用对象属性访问符->替代数组下标[]
        $tmpFileObject->name = $file->sequence->name;
        $tmpFileObject->compiled = true; 
        $tmpFileObject->lineNumbers = $file->sequence->lineNumbers; 
        $tmpFileObject->sequence = $file->sequence->sequence; 
        $tmpFileObject->defTerms = $file->sequence->defTerms; 
        
        $outObj->files[0] = $tmpFileObject; 
        $outObj->filesMotifs = []; 
        $outObj->fileName = "{$file->name}.zip"; 
        $outObj->unknowns = $file->sequence->unknowns; 
        $outObj->motifs = []; 
        $outObj->clusters = []; 
        $outObj->objects = []; 
        
        if (isset($file->objects)) {
            $outObj->objects = $file->objects; 
        }
        
        // 去掉无意义的true参数,若需要格式化JSON可换成JSON_PRETTY_PRINT
        $arrayOfStudentFiles[] = json_encode($outObj); 
    } 
    return $arrayOfStudentFiles; 
}

额外提示

  • 如果你后续需要将JSON字符串转成数组,才需要在json_decode里加第二个参数true,比如json_decode($jsonStr, true);
  • foreach循环中直接使用$file变量(而非$fileArray[$key])能让代码更简洁,也减少出错概率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:02:51