2017-04-08 63 views
-2

我有一個這樣的數組:如何根據特定項目合併數組的行?

$arr = [[1, "red"], 
     [2, "blue"], 
     [3, "yellow"], 
     [1, "green"], 
     [4, "green"], 
     [3, "red"]]; 

,這是預期的結果:

$output = [[1, ["red", "green"]], 
      [2, ["blue"]], 
      [3, ["yellow","red"]], 
      [4, ["green"]]]; 

就是幹這個可以通過PHP?

+0

是有可能在PHP。一個簡單的foreach循環就可以做到。 – Rizier123

+0

'[3,[「黃色」,「紅色」]] - 在您的輸入中沒有「黃色」。更新您的預期輸出 – RomanPerekhrest

回答

0

該結構不是很方便,考慮到你可以使用索引號作爲數組鍵,所以如果是我,我會堅持在我的答案是陣列$ temp創建的結構。總之,你想要的結果,你可以這樣做:

$arr = [[1, "red"], 
      [2, "blue"], 
      [3, "red"], 
      [1, "green"], 
      [4, "green"], 
      [2, "red"]]; 
    $res = array(); 
    $temp = array(); 
    $keys = array(); 
    foreach ($arr as $v) { 
     $temp[$v[0]][] = $v[1]; 
    } 
    foreach (array_keys($temp) as $k) { 
     $res[]=array($k,$temp[$k]); 
    } 

此外,您預期的結果,因爲該指數,看上去更像是:

$output = [[1, ["red", "green"]], 
      [2, ["blue","red"]], 
      [3, ["red"]], 
      [4, ["green"]]]; 
0

這可以通過減少轉換來完成,然後截斷鍵在通過array_values聲明建立所需的輸出之後。

//take only values (re-indexing 0..4) 
$output = array_values(
    //build associative array with the value being a 'tuple' 
    //containing the index and a list of values belonging to that index 
    array_reduce($arr, function ($carry, $item) { 

    //assign some names for clarity 
    $index = $item[0]; 
    $color = $item[1]; 

    if (!isset($carry[$index])) { 
     //build up empty tuple 
     $carry[$index] = [$index, []]; 
    } 

    //add the color 
    $carry[$index][1][] = $color; 

    return $carry; 

    }, []) 
); 
0

使用foreach環和array_values功能簡易的解決方案:

$arr = [[1, "red"], [2, "blue"], [3, "red"], [1, "green"], [4, "green"], [2, "red"]]; 

$result = []; 
foreach ($arr as $pair) { 
    list($k, $v) = $pair; 
    (isset($result[$k]))? $result[$k][1][] = $v : $result[$k] = [$k, [$v]]; 
} 
$result = array_values($result); 
相關問題