【问题标题】:Iterating through multiple arrays and pull data from each one遍历多个数组并从每个数组中提取数据
【发布时间】:2019-12-17 18:32:11
【问题描述】:

我有一个数组,其中包含多个数组(目前为 3 个)。 里面的每个数组都有多个帖子对象。

我正在尝试遍历这 3 个数组,每次从其中一个中拉出 1 个帖子对象,然后将其推送到我创建的新空数组,顺序与我在其他。

// dynamic number
$count_posts_query = 9

//the array that contains 3 arrays with posts in it (dynamic can be more
)
$term_posts = array(
[0] => array( <--- contains 26 posts objects 
   [0] => {post object}.
   [1] => {post object},
   [2] => {post object},
   [... and so on 26 objects] 
 ) 
[1] => array( <--- contains 58 posts objects 
   [0] => {post object}.
   [1] => {post object},
   [2] => {post object},
   [... and so on 58 objects] 
 )
[2] => array( <--- contains 103 posts objects 
   [0] => {post object}.
   [1] => {post object},
   [2] => {post object},
   [... and so on 103 objects] 
 )
),

for ( $i = 0; $i < $count_posts_query; $i ++ ) {
 array_push( $new_terms_arrays, $term_posts[$i][ $i ] );
}

这个循环的问题是 $i 不正确,它只运行了 3 次,每次输入数组的位置和具有相同 $i 编号的对象,然后其他 6 个对象为空而不是升序正确的

错误图像 - https://i.ibb.co/4PxXxgw/Screenshot-at-Aug-10-09-15-20.png

【问题讨论】:

  • 每次都需要相同的帖子吗?你必须确保选择是平衡的吗?例如。每个数组中的帖子数量相同吗?
  • 你的$count_posts_query = 9$term_posts 只有三个数组。
  • $count_posts_query 代表什么?您希望如何使用它来构建您的新阵列?
  • @Scuzzy $count_posts_query 是一个动态数字,表示我想从 $_term_posts 中提取的帖子总数

标签: php arrays wordpress


【解决方案1】:

如果您想遍历数组中的 3 个项目,您可以使用 $term_posts 数组本身的计数,而不是硬编码的 $count_posts_query = 9

for ($i = 0; $i < count($term_posts); $i ++) {
 array_push($new_terms_arrays, $term_posts[$i][$i]);
}

正如Nigel Ren 指出的那样,请注意您将$i 的值用于两个索引。对于第一个工作,因为它基于 $term_posts 数组的计数。

问题出现了,您对第二个数组使用相同的递增索引,但不能保证存在。

如果您想每次拉取 1 个帖子对象,则必须确保使用现有索引。

【讨论】:

    【解决方案2】:

    如果您知道数组的长度总是适合您之后的项目数,您可以使用 array_column() 从每个数组中提取下一组帖子并将其添加到新数组中(使用array_merge())。所以这会从数组中获取所有 [0] 项目,然后是 [1] 项目等等......

    $i=0;
    $new_terms_arrays = [];
    while ( count($new_terms_arrays) < $count_posts_query ) {
        $new_terms_arrays = array_merge( $new_terms_arrays, 
                array_column($term_posts, $i++ ));
    }
    

    【讨论】:

    • 天才!!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多