2012-11-14 112 views
0

我知道這是一個簡單的問題的價值,但我沒有找到答案成功,但...組數組元素相對於另一個陣列

這是組數組元素方面最有效的方法到PHP中另一個數組的值?

例子:

names = [antonio, luigi, marco, stefano, gennaro, pino, lorenzo]; 
surnames = [bianchi, rossi, rossi, brambilla, rossi, rossi, brambilla]; 

預期的結果:

bianchi: 
antonio 

rossi: 
luigi, marco, gennaro, pino 

brambilla: 
stefano, lorenzo 
+0

宥想打印出來,或者創建antoher陣列? –

+0

完美答案,謝謝!選擇「接受」的一個是非常困難的... – andreaconsole

回答

1

試試這個

foreach ($surnames as $key => $value) { 
    if (isset($result[$value])) { 
    if (!is_array($result[$value])) $result[$value] = (array) $result[$value]; 
    array_push($result[$value], $names[$key]); 
    } 
    else 
    $result[$value]= $names[$key]; 
} 
print_r($result); 

輸出

Array (
    [bianchi] => antonio 
    [rossi] => Array ([0] => luigi, [1] => marco, [2] => gennaro, [3] => pino) 
    [brambilla] => Array ([0] => stefano, [1] => lorenzo)  
) 

否則

foreach ($surnames as $key => $value) { $result[$value][] = $names[$key]; } 

輸出

Array (
    [bianchi] => Array ([0] => antonio) 
    [rossi] => Array ([0] => luigi, [1] => marco, [2] => gennaro, [3] => pino) 
    [brambilla] => Array ([0] => stefano, [1] => lorenzo)  
) 
1

這聽起來像你基本上是要創建一個地圖,地圖上的每個輸出單元是列表。嘗試是這樣的:

<?php 
function groupArrays($arrayToGroup, $arrayToGroupBy) 
{ 
    if (count($arrayToGroup) != count($arrayToGroupBy)) 
     return null; 

    $output = array(); 
    for ($i = 0; $i < count($arrayToGroupBy); $i++) 
    { 
     $key = $arrayToGroupBy[$i]; 
     $val = $arrayToGroup[$i]; 

     if (!isset($output[$key])) 
      $output[$key] = array(); 

     array_push($output[$key], $val); 
    } 

    return $output; 
} 
?> 
1

我只是快速創建腳本,這是最快的和可靠的方式:

<?php 
$names = ['antonio', 'luigi', 'marco', 'stefano', 'gennaro', 'pino', 'lorenzo']; 
$surnames = ['bianchi', 'rossi', 'rossi', 'brambilla', 'brambilla', 'brambilla', 'brambilla']; 

$final = []; 
foreach ($surnames as $index => $_sur) { 
    // We don't check isset $names[$index] here 
    $final[$_sur][] = $names[$index]; 
} 

var_export($final); 
相關問題