按值合并单个数组对象并保留子数组中的重复项

时间:2017-04-27 10:59:34

标签: php arrays sorting merge unique

我有以下(简化)数组:

$myArray = array(
   0=> array( 
      'userid' => '12',
      'favcolor' => 'green'
   ),
   1=> array( 
      'userid' => '62',
      'favcolor' => 'orange'
   ),
   2=> array( 
      'userid' => '12',
      'favcolor' => 'red'
   ),
   3=> array( 
      'userid' => '62',
      'favcolor' => 'blue'
   ),
)

我想通过常用的userid值合并数组,并保留fav颜色信息。我尝试过的其他方法只保留数组中的第一个favcolor值。看似简单,但无法找到快速解决方案。

预期输出:

$myArray = array(
   0=> array( 
      'userid' => '12',
      'favcolor' => array('green', 'red')
   ),
   1=> array( 
      'userid' => '62',
      'favcolor' => array('orange', 'blue')
   ),
)

如果不使用另一个数组进行比较,这是否可行?

2 个答案:

答案 0 :(得分:0)

这里我们使用简单的foreach来合并并实现预期的结果,将此数组的userid用作key。这里我们使用array_values删除这些密钥。

Try this code snippet here

<?php

ini_set('display_errors', 1);

$myArray = array(
   0=> array( 
      'userid' => '12',
      'favcolor' => 'green'
   ),
   1=> array( 
      'userid' => '62',
      'favcolor' => 'orange'
   ),
   2=> array( 
      'userid' => '12',
      'favcolor' => 'red'
   ),
   3=> array( 
      'userid' => '62',
      'favcolor' => 'blue'
   ),
);
$result=array();
foreach($myArray as $value)
{
    //check for previous existence of key in resultant array
    //if key not exist then put value on that key and using favcolor as array
    if(!isset($result[$value["userid"]]))of key in a array.
    {
        $result[$value["userid"]]=array("userid"=>$value["userid"],"favcolor"=>array($value["favcolor"]));
    }
    //if key already exists then just adding favcolor values to that key
    else
    {
        $result[$value["userid"]]["favcolor"][]=$value["favcolor"];
    }
}
print_r(array_values($result));

<强>输出:

Array
(
    [0] => Array
        (
            [userid] => 12
            [favcolor] => Array
                (
                    [0] => green
                    [1] => red
                )

        )

    [1] => Array
        (
            [userid] => 62
            [favcolor] => Array
                (
                    [0] => orange
                    [1] => blue
                )

        )

)

答案 1 :(得分:0)

只需按以下步骤操作

// Creating an array for result
foreach($myArray as $ar){
    if(!isset($aa[$ar['userid']])) $aa[$ar['userid']] = [];
    if(!in_array($ar['favcolor'],$aa[$ar['userid']])) $aa[$ar['userid']][] = $ar['favcolor'];
}

// Designing it according to result
foreach($aa as $arr=>$val)
    $last[] =  ['userid'=>$arr,'favcolor'=>$val];

echo '<pre>';
var_dump($last);