2013-01-06 58 views
1

我怎麼能合併這三個數組PHP多個陣列以一個關聯數組

$name ={"Tom", "John", "David"}; 
$v1 = {"Tom":100, "David":200}; 
$v2 = {"John":500, "Tom":400}; 

成一個多維關聯數組中兩種不同的方式? 一種方法是鍵的順序應該與數組「名稱」的順序相同。

$name_merged_original_order = array (
    "Tom" => Array(
     "v1" => 100, 
     "v2" => 400 
    ), 
    "John" => Array(
     "v1" => "N/A", 
     "v2" => 500 
    ), 
    "David" => Array(
     "v1" => 100, 
     "v2" => "N/A" 
    ) 
) 

另一種方式是數組「名稱」的字母:

$name_merged_asc = array (
    "David" => Array(
     "v1" => 100, 
     "v2" => "N/A" 
    ), 
    "John" => Array(
     "v1" => "N/A", 
     "v2" => 200 
    ), 
    "Tom" => Array(
     "v1" => 100, 
     "v2" => 400 
    ), 
) 

棘手的部分是陣列「V1」和「V2」不排序爲重點「的名字。」他們也沒有「名字」中的所有鍵。謝謝!

回答

2

這不是測試,最簡單的解決方案:

$name_merged_original_order = array(); 
foreach($name as $key){ 
    $name_merged_original_order[$key] = array(); 
    if(array_key_exists($key, $v1)){ 
     $name_merged_original_order[$key]['v1'] = $v1[$key]; 
    } 
    else{ 
     $name_merged_original_order[$key]['v1'] = 'N/A'; 
    } 
    if(array_key_exists($key, $v2)){ 
     $name_merged_original_order[$key]['v2'] = $v2[$key]; 
    } 
    else{ 
     $name_merged_original_order[$key]['v2'] = 'N/A'; 
    } 
} 

sort($name); 
$name_merged_asc = array(); 
foreach($name as $key){ 
    $name_merged_asc[$key] = array(); 
    if(array_key_exists($key, $v1)){ 
     $name_merged_asc[$key]['v1'] = $v1[$key]; 
    } 
    else{ 
     $name_merged_asc[$key]['v1'] = 'N/A'; 
    } 
    if(array_key_exists($key, $v2)){ 
     $name_merged_asc[$key]['v2'] = $v2[$key]; 
    } 
    else{ 
     $name_merged_asc[$key]['v2'] = 'N/A'; 
    } 
} 
+0

這個作品!非常感謝你。 – clerksx

+0

你不客氣。這是在德國的上午6點,我把我的頭撞在聯合陣列上:) – bitWorking

+0

danke danke gute nacht !! – clerksx

0

從匹配所有3個數組,你的意見,你只想項目假設:

for($i=0; $i< count($name) ; $i++){ 
    if(!empty($v1[ $name[$i]]) && !empty($v2[ $name[$i]])){ 
     $newArray[$name[$i]]= array('v1'=> $v1[ $name[$i]], 'v2'=> $v2[ $name[$i]]): 
    } 
} 

排序:

asort($newArray); 
+0

謝謝,但我只是簡單的舉例。我想了解一般方法。 – clerksx

1

據我所知,你會喜歡這樣的事情:

$name = array("Tom", "John", "David"); 
$result = array(); 
$v1 = array("Tom" => "200", "John" => "100", "David" => "10"); 
$v2 = array("Tom" => "254", "David" => "156"); 
$vars = array("v1", "v2"); 
foreach($name as $n) 
{ 
    $result[$n] = array(); 
    foreach($vars as $v) 
    { 
    if(array_key_exists($n, ${$v})) 
     $result[$n][$v] = ${$v}[$n]; 
    } 
} 

我希望$result是你所需要的。

+0

非常感謝,它非常簡單,但如果密鑰不存在,我仍然需要「N/A」值。但仍然偉大和簡單的解決方案! – clerksx

+0

歡迎您!嘗試添加else語句'else $ result [$ n] [$ v] =「N/A」;' – 2013-01-06 05:23:50

1

例如,你有這些陣列:

<?php 
$FirstArrays = array('a', 'b', 'c', 'd'); 
$SecArrays = array('1', '2', '3', '4'); 

1)

foreach($FirstArrays as $index => $value) { 
    echo $FirstArrays[$index].$SecArrays[$index]; 
    echo "<br/>"; 
} 

或2)

for ($index = 0 ; $index < count($FirstArrays); $index ++) { 
    echo $FirstArrays[$index] . $SecArrays[$index]; 
    echo "<br/>"; 
}