2017-04-08 44 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); 
相关问题