Marco
Marco

Reputation: 76

Sort and merge a multidimensional array by common value

I have a multidimensional array and I'm trying to sort it by common value of one particular key, name in my case.

I already tried using a foreach to loop into the array, or using usort, but I just can't find the way to do it.

Notice how the values of the "Diamètre" key are merged into an array in the final result.

Array
(
    [0] => Array
        (
            [0]  => Array
                (
                    [name]  => Diamètre
                    [value]  => 5                   
                )

            [1]  => Array
                (
                    [name]  => Force
                    [value]  => 30                  
                )

        )

    [1]  => Array
         (

            [0]  => Array
                (
                    [name]  => Force
                    [value]  => 20             
                )

            [1]  => Array
                (
                    [name]  => Poids
                    [value]  => 50         
                )
          )
     [2]  => Array
         (
            [0]  => Array
                (
                    [name]  => Diamètre
                    [value]  => 40
                )

            [1]  => Array
                (
                    [name]  => Largeur
                    [value]  => 40
                )

          )
)

Expected result :

Array
(

            [0]  => Array
                (
                    [name]  => Diamètre
                    [value]  => Array (5, 40)                                                              
                )

            [1]  => Array
                (
                    [name]  => Force
                    [value]  => Array (30, 20)               
                )

             [2]  => Array
                 (
                    [name]  => Poids
                    [value]  => 50        
                 ) 

             [3]  => Array
               (
                    [name]  => Largeur
                    [value]  => 40
                )     
)

Upvotes: 0

Views: 74

Answers (1)

Mkk
Mkk

Reputation: 443

You could try something along the lines of:

$result = [];

foreach($array1 as $array2) {
    foreach($array2 as $item) {

        if(array_key_exists($item['name'], $result)) {
            $newItem = $result[$item['name']];

            $valueArray = (array) $item['value'];
            $newValueArray = (array) $newItem['value'];

            $newItem['value'] = array_merge($valueArray, $newValueArray);
        } else {
            $newItem = $item;
        }

            $result[$item['name']] = $newItem;
    }
}

// In case you don't want an associative array.
$result = array_values($result);

Upvotes: 1

Related Questions