PHP:Foreach为索引不正确的数组访问值
我有一个api调用提供的索引,如下所示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] =>
(
[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建议的方法相比,它是有效的