0

Here is the array which I have,

Array
(
    [0] => Array
        (
            [number] => 2
            [name] => ABC
        )

    [1] => Array
        (
            [number] => 3
            [name] => ABC
        )

    [2] => Array
        (
            [number] => 1
            [name] => XYZ
        )

    [3] => Array
        (
            [number] => 2
            [name] => XYZ
        )
)

what I want is...

Array
(
    [0] => Array
        (
            [name] => XYZ
            [number] => 1,2
        )

    [1] => Array
        (
            [name] => ABC
            [number] => 2,3
        )
)

it should be unique by name.

And numbers of particular name will be in comma separated.

please help me guys

Thanks in advance

Jay Patel
  • 305
  • 2
  • 6
  • 20

3 Answers3

0

You can do this in one loop but I prefer to do it in two loops as it will be easier to get the correct output with implode than adding commas and then removing them again.

Loop the array and build an associative array and make an array to collect the numbers.
Then loop again and implode the numbers to a string.

foreach($arr as $sub){
    $res[$sub['name']]['name'] = $sub['name'];
    $res[$sub['name']]['number'][] = $sub['number'];
}

foreach($res as &$sub){
    $sub['number'] = implode(",", $sub['number']);
}
$res = array_values($res);
var_dump($res);

https://3v4l.org/PbGsu

Andreas
  • 23,610
  • 6
  • 30
  • 62
0

You can use array_map, array_key_exists, array_values to get the desired results

$res = [];
array_map(function($v) use (&$res){
array_key_exists($v['name'], $res) ?
        ($res[$v['name']]['number'] = $res[$v['name']]['number'].','.$v['number'])
        :
        ($res[$v['name']] = ['number' => $v['number'],'name'   => $v['name']])
        ;
}, $arr);
$res = array_values($res);

Live Demo

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
-1

To use

array_merge()

function. If suppose your key values are same, your key and values are overwrites after merge your array.

Arun Ranga
  • 47
  • 6