2015-01-04 101 views
-1

我有3 陣列,所有相同的數字,我需要合併到一個3d陣列在PHP中合併3個陣列爲3d陣列

因此,像:

array1 = 'aud', 'usd', 'usd' 
array2 = 'item 1', item 2', 'item 3' 
array3 = '100', 300', 500' 

我需要製作喜歡的數組:

new_array1 = 'aud', 'item 1', '100' 
new_array2 = 'usd', 'item 2', '300' 

我已嘗試打印無下列情況:

$item = array(); 
for($i=0; $i < sizeof($currencies); $i++) { 
    $item[$i] = array('curr' => $currencies[$i], 
          'name' => $events[$i], 
          'result' => $actuals[$i]); 

} 

print_r($item); 

回答

0

你必須當我得到正確的資源時會做錯事ULT與此腳本:

$arr1 = [ "aud", "usd", "usd" ]; 
$arr2 = [ "item 1", "item 2", "item 3" ]; 
$arr3 = [ 100, 300, 500 ]; 

$nestedArr = []; 

for($i = 0; $i < count($arr1); $i++) { 
    $nestedArr[$i] = [ 
     "curr" => $arr1[$i], 
     "name" => $arr2[$i], 
     "result" => $arr3[$i] 
    ]; 
} 

print_r($nestedArr); 

輸出:

Array (
    [0] => Array (
    [curr] => aud 
    [name] => item 1 
    [result] => 100 
) 
    [1] => Array (
    [curr] => usd 
    [name] => item 2 
    [result] => 300 
) 
    [2] => Array (
    [curr] => usd 
    [name] => item 3 
    [result] => 500 
) 
) 

請注意,我用PHP陣列短語法聲明數組[],不應該有所作爲。這是很好的做法。

0

嗯,你的代碼應該產生一個二維數組,嘗試在

$item[$i] = array('curr' => $currencies[$i], 

刪除$i所以它看起來像這樣:

$item[] = array('curr' => $currencies[$i], 

還添加了3D陣列,您應該etiher靜態創建,像這樣:

$item = array(
    'usd' => array(
     item1 => array("100" => 100, "200" => 200, "300" => 300), 
     item2 => array("100" => 100, "200" => 200, "300" => 300), 
     item3 => array("100" => 100, "200" => 200, "300" => 300), 
    ), 
    'eur' => array(
     item1 => array("100" => 100, "200" => 200, "300" => 300), 
     item2 => array("100" => 100, "200" => 200, "300" => 300), 
     item3 => array("100" => 100, "200" => 200, "300" => 300), 
    ), 
    'gbp' => array(
     item1 => array("100" => 100, "200" => 200, "300" => 300), 
     item2 => array("100" => 100, "200" => 200, "300" => 300), 
     item3 => array("100" => 100, "200" => 200, "300" => 300), 
    ), 
), 
+0

downvote的任何理由? – Richard87 2015-01-04 13:07:30

+0

你爲什麼要嵌套循環?這是一個可怕的想法。 $貨幣將迭代4次,$ items將迭代16次,$ values將迭代64次。爲什麼迭代84次這麼簡單? – Svenskunganka 2015-01-04 13:09:23

+0

那麼,如果你使用緩存,並有一個更復雜的值列表,請注意我提供了2個選項來創建3D數組,一個快速,另一個用於更大的列表... – Richard87 2015-01-04 13:11:18