基于相同的键连接数组值

时间:2014-06-28 20:24:29

标签: php arrays merge associative-array

延伸到我的上一个问题,我有一个如下数组:

 Array
(
    [0] => Array
        (
            [id] => 1
            [uid] => 746
            [lid] => 748
        )

   [1] => Array
        (
            [id] => 6
            [uid] => 746
            [lid] => 744
        )

   [2] => Array
        (
            [id] => 11
            [uid] => 749
            [lid] => 743
        )


)

我现在想要的是将值与应输出的相同uid合并为:

 Array
(
    [0] => Array
        (
            [id] => 1,6
            [uid] => 746
            [lid] => 748,744
        )

   [1] => Array
        (
            [id] => 11
            [uid] => 749
            [lid] => 743
        )


)

有可能吗?我不知道它是否有任何功能。

3 个答案:

答案 0 :(得分:1)

如果您要在数据库中插入此内容,请不要执行this,因为这会长期困扰您。无论如何,没有内置函数可以做到这一点。你只需要一个简单的foreach循环。考虑这个例子:

$new_values = array();
$values = array(
    array('id'=> 1, 'uid' => 746, 'lid' => 748),
    array('id'=> 6, 'uid' => 746, 'lid' => 744),
    array('id'=> 11, 'uid' => 749, 'lid' => 743),
);

foreach($values as $value) {
    if(isset($new_values[$value['uid']])) {
        $temp = $new_values[$value['uid']];
        $temp['id'] .= ',' . $value['id'];
        $temp['lid'] .= ',' . $value['lid'];
        $new_values[$value['uid']] = $temp;
    } else {
        $new_values[$value['uid']] = $value;
    }
}

$new_values = array_values($new_values); // reindex keys

Sample Output

答案 1 :(得分:0)

我建议构建一个uid-Array(假设你的数组在$ array中):

$uid_array = array();
foreach($array as $key => $val) {
  $uid = $val["uid"];
  if(! isset($uid_array[$uid])) {
    $uid_array[$uid] = array();
  }
  if(! isset($uid_array[$uid]["id"])) {
    $uid_array[$uid]["id"] = $val["id"];
  } else {
    $uid_array[$uid]["id"].= ",".$val["id"];
  }
  if(! isset($uid_array[$uid]["lid"])) {
    $uid_array[$uid]["lid"] = $val["lid"];
  } else {
    $uid_array[$uid]["lid"].= ",".$val["lid"];
  }
}

答案 2 :(得分:0)

我不知道哪种功能可以满足您的需求,但这样可以满足您的需求:

function myArrayMerge($arr)
{
    $result = array();
    foreach($arr as $user_array)
    {
        $result[$user_array['uid']]['id'][$user_array['id']] = $user_array['id'];
        $result[$user_array['uid']]['lid'][$user_array['lid']] = $user_array['lid'];
    }

    $output = array();
    foreach($result as $uid => $result_array) {
        $output[] = array('id' => implode(',', $result_array['id']), 'uid' => $uid, 'lid' => implode(',', $result_array['lid']));
    }
    return $output;
}