PHP - 如何将数组附加到具有特定键和值的另一个数组中?

时间:2014-04-15 14:22:07

标签: php arrays associative-array

如果可能,我不会,但我有两个阵列。数组一个是这样的:

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

我有另一个阵列:

Array ( [0] => WP_Post Object ( [ID] => 83 [post_author] => 1 [post_date] => 2014-03-05 16:30:45 [post_date_gmt] => 2014-03-05 16:30:45)
        [1] => WP_Post Object ( [ID] => 33 [post_author] => 1 [post_date] => 2014-03-05 16:30:45 [post_date_gmt] => 2014-03-05 16:30:45)
        [2] => WP_Post Object ( [ID] => 34 [post_author] => 1 [post_date] => 2014-03-05 16:30:45 [post_date_gmt] => 2014-03-05 16:30:45)
        [3] => WP_Post Object ( [ID] => 80 [post_author] => 1 [post_date] => 2014-03-05 16:30:45 [post_date_gmt] => 2014-03-05 16:30:45) )

是否可以使用特定键将第一个数组的每个值添加到第二个数组中:例如:

Array (     [0] => WP_Post Object ( [ID] => 83 [post_author] => 1 [post_date] => 2014-03-05 16:30:45 [post_date_gmt] => 2014-03-05 16:30:45 [post_permalink] => link)
            [1] => WP_Post Object ( [ID] => 33 [post_author] => 1 [post_date] => 2014-03-05 16:30:45 [post_date_gmt] => 2014-03-05 16:30:45 [post_permalink] => link)
            [2] => WP_Post Object ( [ID] => 34 [post_author] => 1 [post_date] => 2014-03-05 16:30:45 [post_date_gmt] => 2014-03-05 16:30:45 [post_permalink] => link)
            [3] => WP_Post Object ( [ID] => 80 [post_author] => 1 [post_date] => 2014-03-05 16:30:45 [post_date_gmt] => 2014-03-05 16:30:45 [post_permalink] => link) )

我尝试了 array_merge ,但这使得两个子数组成为一个数组。有没有办法可以达到上述效果。任何帮助将受到高度赞赏。感谢

我的数组的PHP代码:

<?php 
     $postids = array();
     $value = array();
     if ( $the_query->have_posts() ) { ?>

     while ($the_query->have_posts()) : $the_query->the_post(); 

     $postids[]=$the_query->post; 

     $value[] = get_permalink();

    ?>


    <?php endwhile; ?>

1 个答案:

答案 0 :(得分:2)

在将其放入$postids数组之前,您应该只需将其添加到post对象:     

$postids = array();
if ($the_query->have_posts()) {
    while ($the_query->have_posts()) {
        $the_query->the_post();
        $the_query->post->post_permalink = get_permalink();
        $postids[] = $the_query->post;
    }
}