首页 > 解决方案 > PHP:Foreach 访问不正确索引数组的值

问题描述

我的 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 
      }
    }

我该怎么做,请指教

标签: phpcodeigniterforeach

解决方案


看起来您正在“成对”获取数据。索引 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"
}

推荐阅读