php - 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
}
}
我该怎么做,请指教
解决方案
看起来您正在“成对”获取数据。索引 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"
}
推荐阅读
- xcode - Xcode 移除重复的 Pod 框架
- machine-learning - Pytorch 中 GRU 单元的隐藏和输出是否相同?
- liferay - 避免 Liferay 资产 URL 中的端口号
- typescript - 将标签转换为标签数组
- c++ - NHWC 与 NCHW 的好处
- spring - 异步事件侦听器的默认 TaskExecutor 实现
- sql-server - 如何在具有 1.5 亿条记录的表中提高 SQL Server 上的查询性能?
- python - np.squeeze 进行作业
- java - 在 AOP 中为 @Async 方法处理异常时丢失 HttpServletRequest 对象
- discord.js - 尝试在我的不和谐机器人上实现仅 Patreon 的命令/功能,我将如何实现这一点?