Ayman Hussein
Ayman Hussein

Reputation: 3857

merge php array elements that have the same name

I have this php array

array [
    [0] => array [
                   name => 'a',
                   service => 'x1' 
                 ],
    [1] => array [
                   name => 'a',
                   service => 'x2' 
                 ],
    [2] => array [
                   name => 'a',
                   service => 'x3' 
                 ],
    [3] => array [
                   name => 'b',
                   service => 'x1' 
                 ],
    [4] => array [
                   name => 'b',
                   service => 'x3' 
                 ],
    [5] => array [
                   name => 'b',
                   service => 'x5' 
                 ]
]

what I want to marage all a's service in one element and b as well like the following:

array [
    [0] => array [
                   name => 'a',
                   service => 'x1, x2, x3' 
                 ],
    [1] => array [
                   name => 'b',
                   service => 'x1, x3, x5' 
                 ]
]

php code:

$new_services = array(); 
foreach($services as $service) {
      if (isset($new_services[$service->name])) {
           $new_services[$service->name] .= $service['name'].',';
      }
      else{ 
         $new_services[$service->name] = $service['service'];
      }
}

the expected result is not the same what I want.

Upvotes: 1

Views: 2949

Answers (1)

Rizier123
Rizier123

Reputation: 59701

This should work for you:

Just go through each sub array and check if you have a sub array in your $result array with the name as index. If not add it to the result array. If you already have a key with the name, just append the service value to it. At the end just reindex the array with array_values().

<?php

    $result = [];
    foreach($arr as $v) {
        if(!isset($result[$v["name"]])) {
            $result[$v["name"]]["name"] = $v["name"];
            $result[$v["name"]]["service"] = $v["service"];
        } else {
            $result[$v["name"]]["service"] .= ", " . $v["service"];
        }
    }

    $result = array_values($result);
    print_r($result);

?>

output:

Array
(
    [0] => Array
        (
            [name] => a
            [service] => x1, x2, x3
        )

    [1] => Array
        (
            [name] => b
            [service] => x1, x3, x5
        )

)

Upvotes: 3

Related Questions