2012-07-10 39 views
2

問題是這樣的...按相同的數組鍵旁邊

現有陣列:

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>'; 

回答

5

您與array_splice做到這一點:

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

Ex充足的:

$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)); 
+0

Maxhud我編輯了我的問題。小心看看我的片段。謝謝! – Ian 2012-07-10 16:21:57

+0

是一個$ the_post等價於你的例子中提到的'樣本'?意思是,$ the_post變量存儲什麼?它是一個包含兩個項目的數組還是一個字符串? – maxhud 2012-07-10 16:33:01

+0

$ the_post變量是一個數組。 – Ian 2012-07-10 16:35:45