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

3

我收到一个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 
      }
    }

请问我该如何做?请给予建议。

2个回答

3

看起来你正在以“一组”数据的形式获取数据。索引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"
}

1
这也是一个不错的方法,与@azibom建议的方法相比,哪个更有效率。 - Sikander Nawaz

2

只需尝试以下操作:


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";
    }
}

$xml = $array[$key + 1]; 这个可以工作,谢谢。 - Sikander Nawaz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接