Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:Foreach为索引不正确的数组访问值_Php_Codeigniter_Foreach - Fatal编程技术网

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

PHP:Foreach为索引不正确的数组访问值,php,codeigniter,foreach,Php,Codeigniter,Foreach,我有一个api调用提供的索引,如下所示 ( [0] => stdClass Object ( [xml] => [qid] =>1 [title] => Tile of the question [description] => Description of the question here ) [1] =>

我有一个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($key=>$node的数组){
试一试{
$title=$node->title;
$des=$node->description;
$qid=$node->qid;
如果($node->xml==''){
$xml=$array[$key+1];
}
echo“添加了索引为$key的行”;
}捕获(\Throwable$th){
echo“那是一个xml行-键是$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"
}

$xml=$array[$key+1];这很有效,谢谢。这也是一个很好的方法,与@azibom建议的方法相比,它是有效的