代码工作,如果请求返回多个对象,如果请求只返回一个错误


Code works if request returns multiple objects, error if request returns only one

我正试图根据他们在什么行业工作来获取候选人。当我在一个只有一个(JSON格式)的行业中发送候选人请求时,我的请求返回此数据:

 stdClass Object ([Candidates] => stdClass Object ([row] =>
 stdClass Object ([no] => 1 [FL] => Array ( 
    [0] => stdClass Object ( [content] => 213748000001275022 [val] => RESUMEID ) 
    [1] => stdClass Object ( [content] => John (3) [val] => Modified by ) 
    [2] => stdClass Object ( [content] => 11 Aug-2015 [val] => Modified time ) 
    [3] => stdClass Object ( [content] => 3308 [val] => Candidate ID ) 
    [4] => stdClass Object ( [content] => John (3) [val] => Recruiter ) 
    [5] => stdClass Object ( [content] => Creative arts [val] => Branche / Industry ) 
    [6] => stdClass Object ( [content] => Ja / Yes [val] => Accept af optagelse i Kandidatbank / Accept my registration in
 candidatedatabase )))))

我使用以下代码:

$rowArray = $data->response->result->Candidates->row;
for ($i = 0; $i < count($rowArray); $i++) {            
      $FL = $data->response->result->Candidates->row[$i]->FL;
}

确切的错误我得到的是,我"不能使用stdClass类型的对象作为数组",但为什么这个错误现在?我在处理其他请求时完全没问题。为了用一些代码进一步解释一些事情,下面是$FL的用途:

if (array_key_exists(4, $FL) === true && $FL[4]->val === 'Branche / Industry') {
      $industry = $FL[4]->content;
} else if (array_key_exists(5, $FL) === true && $FL[5]->val === 'Branche / Industry') {
      $industry = $FL[5]->content;
} else {
      $industry = $notSpecified;
}

它在我的PHP代码中设置候选变量,以便我可以在表中显示它。

您可以按照以下步骤进行操作-1. 首先检查它是否是一个数组,然后像往常一样2. 否则创建一个数组并将其压入,然后按常规操作

$rowArray = $data->response->result->Candidates->row;
        if(!is_array($rowArray))
        {
        $rowArray=array($data->response->result->Candidates->row);
        //so that $rowArray is now an array and count gives 1
        }

应该可以:

$FL = $data->response->result->Candidates->row->FL[$i];

它告诉你"不能使用stdClass类型的对象作为数组",因为你正试图这样做;像访问数组一样访问对象。也许你的服务器根据你发送的特定请求返回了不同的数据结构。