在它旁边按一个相同的数组键

时间:2012-07-10 15:56:21

标签: php arrays

问题是这样的......

现有数组:

Array(
    [0] => array('sample 1', 'sample 2')
    [1] => array('cat', 'dog')
)

另一个阵列:

Array(
    [0] => array('sample 3', 'sample 4')
)

我希望将它添加到0键旁边,以便它成为:

Array(
    [0] => array('sample 1', 'sample 2')
    [1] => array('sample 3', 'sample 4')
    [2] => array('cat', 'dog')
)

你是怎么做到的?

@maxhud 我尝试了但是结果是这样的:

Array(
[0] => sample 1
[1] => sample 2
[2] => sample 3
[3] => sample 4
[4] => cat
[6] => dog
)

这是我当前的当前代码段

$new_post_order = array();
foreach($the_query['posts'] as $the_post) {
$portfolio_reorder = '';
$portfolio_reorder = get_post_meta($the_post['ID'], 'portfolio_reorder', true); // Get the order on the db
if(empty($portfolio_reorder)) { // If its empty...
 $portfolio_reorder = 0; // Add default order                           
}
 array_splice($new_post_order, $portfolio_reorder, 0, $the_post);
}

echo '<pre>';
print_r( $new_post_order );
echo '</pre>';

1 个答案:

答案 0 :(得分:5)

您可以使用array_splice完成此操作:

http://php.net/manual/en/function.array-splice.php

示例:

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green",
//          "blue", "purple", "yellow");

自己尝试一下,如果你无法弄明白,请发表评论,我们会帮助你。

array_splice($new_post_order, $portfolio_reorder, 0, array($the_post));