【问题标题】:PHP - How to combine arrays into one array in while loop?PHP - 如何在while循环中将数组组合成一个数组?
【发布时间】:2014-05-29 22:15:28
【问题描述】:

我有这段代码,它在一个while循环中给了我post_permalink

<?php 
  $value[] = array();
    while ($the_query->have_posts()) : $the_query->the_post()
                $value[] =array(
                    'post_permalink' => get_permalink()
                );

 endwhile; ?>

现在问题是我得到了links

    Array ( [0] => Array ( [post_permalink] => link ) 
            [1] => Array ( [post_permalink] => link ) 
            [2] => Array ( [post_permalink] => link ) 
            [3] => Array ( [post_permalink] => link ) )

我想要的样子:

        Array ( [post_permalink] => link  
                [post_permalink] => link 
                [post_permalink] => link 
                [post_permalink] => link  )

即:一个数组中的所有链接,而不是四个子数组。请帮忙!

【问题讨论】:

  • 你说你想要的结果有多次相同的索引。我不认为这实际上是你想要的。
  • 你的数组必须有唯一的键。真的没有办法解决这个问题。
  • 是的,如果可能的话,我希望每个值都有相同的索引
  • "如果可能的话" 不是。
  • 在尝试一堆事情之前,您可能应该花更多时间弄清楚您想要完成的确切目标是什么,以及完成该目标的结果应该是什么。

标签: php arrays multidimensional-array while-loop


【解决方案1】:

您不能以您想要的方式拥有一个数组,因为每个数组键都必须是唯一的。这将起作用:

$values = array();
while($the_query->have_posts()) : $the_query->the_post();
    $values[] = get_permalink();
endwhile;

【讨论】:

【解决方案2】:

您想要的示例是不可能的,因为数组键是唯一的。

你可能想要这样的东西:

$value['post_permalink'][] = get_permalink();

【讨论】:

    【解决方案3】:
    foreach($value[0] as $k=>$v)
       $result[$k]=$v
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-18
      • 2012-02-24
      • 2012-02-21
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      相关资源
      最近更新 更多