我的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
}
}我该怎么做呢?请告诉我
发布于 2020-12-25 22:44:34
试着这样做:
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";
}
}发布于 2020-12-25 22:46:41
看起来你是在“成对”地获取数据。索引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"
}https://stackoverflow.com/questions/65448982
复制相似问题