James
James

Reputation: 318

Concatenate array values based on same keys

Extending to my last question, I have an array like below:

 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
        )


)

What I want now is to merge the values with the same uid which should output as:

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

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


)

Is it possible? I don't know if there is any function for it.

Upvotes: 3

Views: 2785

Answers (3)

user1978142
user1978142

Reputation: 7948

If you're going to insert this inside the database, don't do this because this will bite you in the long term. Anyway, there is no built-in function that does this. You just need a simple foreach loop. Consider this example:

$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

Upvotes: 1

Bob S
Bob S

Reputation: 23

I'm not aware of a function that will give you what you are looking for, but this will give you what you want:

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;
}

Upvotes: 0

hellcode
hellcode

Reputation: 2698

I suggest to build a uid-Array (assuming your array is in $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"];
  }
}

Upvotes: 0

Related Questions