PHP: Foreach 访问索引不正确的数组的值

PHP: Foreach accessing values for improperly indexed array

我的 api 调用提供了一个不正确的索引,如下所示

(
    [0] => stdClass Object
        (
            [xml] =>  
            [qid] =>1
            [title] => Tile of the question 
            [description] => Description of the question here
        )

    [1] => xml for quetion 1 
    [2] => stdClass Object
        (
            [xml] =>  
            [qid] => 2
            [title] => Updated Question 
            [description] => description changed for edting
        )

    [3] => xml for quetion 2  
)

我可以访问 foreach 循环中的值,但问题是每个问题的 xml 被设置在循环的下一个索引中:

foreach ($array as  $key =>$node) {
     $title = $node->title;
     $des = $node->description;
     $qid = $node->qid;
     if($node->xml==''){
         // set xml value here in 1  and 3 index seen as in above output 
      }
    }

我该怎么做,请指教

试试这个:


foreach ($array as  $key =>$node) {
    try {
        $title = $node->title;
        $des = $node->description;
        $qid = $node->qid;
        if($node->xml==''){
            $xml = $array[$key + 1];
        }
        echo "Added row with index $key";
    } catch (\Throwable $th) {
        echo "That was a xml row - The key is $key";
    }
}

看起来您正在“成对”获取数据。索引 0 和 1 属于一起,2 和 3 等等。

如果是这样,您可以将数据分成块并处理每一对:

$chunks = array_chunk($array, 2);
foreach($chunks as $chunk) {
    // $chunk[0] contains object with title, qid, ...
    // $chunk[1] contains "xml for question"
}