2012-09-19 159 views
-3

我有一個數組,我需要通過鍵合併使用該鍵的值創建一個新數組。我搜索並沒有結果搜索。任何幫助將是偉大的!按鍵合併數組,併爲值創建一個新數組

原始陣列

Array 
(
    [0] => Array 
    (
     [name] => Key 1 
     [value] => Value 1 
    ) 

    [2] => Array 
    (
     [name] => Key 1 
     [value] => Value 2 
    ) 

    [3] => Array 
    (
     [name] => Key 2 
     [value] => Value 1 
    ) 

    [4] => Array 
    (
     [name] => Key 1 
     [value] => Value 3 
    ) 

    [5] => Array 
    (
     [name] => Key 2 
     [value] => Value 2 
    ) 
) 

最終陣列應該是這樣的

Array 
(
    [0] => Array 
    (
     [name] => Key 1 
     [value] => Array 
     (
      [0] => Value 1 

      [1] => Value 2 

      [2] => Value 3 
     ) 
    ) 

    [1] => Array 
    (
     [name] => Key 2 
     [value] => Array 
     (
      [0] => Value 1 

      [1] => Value 2 
     ) 
    ) 
) 
+0

正如前面問,你有什麼嘗試,發佈一些工作代碼,無所謂是不正確的,是一個起點,也許你離這裏不遠解決方案 – Yaroslav

回答

1
<?php 
$array = Array 
(
    0 => Array 
    (
     'name' => 'Key 1', 
     'value' => 'Value 1' 
    ), 

    2 => Array 
    (
     'name' => 'Key 1', 
     'value' => 'Value 2' 
    ), 

    3 => Array 
    (
     'name' => 'Key 2', 
     'value' => 'Value 1' 
    ), 

    4 => Array 
    (
     'name' => 'Key 1', 
     'value' => 'Value 3' 
    ), 

    5 => Array 
    (
     'name' => 'Key 2', 
     'value' => 'Value 2' 
    ) 
); 
$tmpArray = array(); 
foreach ($array as $smallArray) { 
if(!is_array($tmpArray[$smallArray['name']])) 
    $tmpArray[$smallArray['name']] = array(); 

$tmpArray[$smallArray['name']][] = $smallArray['value']; 
} 
$finalArray = array(); 
foreach ($tmpArray as $key => $value) { 
    $someArray['name'] = $key; 
    $someArray['value'] = $value; 
    $finalArray[] = $someArray; 
} 

print_r($finalArray); 

我寫的爲你解決,但下一次你應該嘗試你的自我第一

+0

相信我,我已經嘗試過! :)我坐了整夜,測試不同的東西。我終於設法解決了這個問題。看起來不像你的代碼,但它也可以。感謝您的幫助! :) – user1682488