Put the elements of the array with the same value in one element and connect their keys

I am trying to combine / add the keys of an array that contains the same values.

I have an array like this:

$array = array(
           '12' => 'Coats',
           '23' => 'Coats',
           '45' => 'Brushs',
           '5'  => 'others',
           '7'  => 'None',
           '8'  => 'None',
           '9'  => 'None',
         );

Expected Result:

$array = array(
           '12,23' => 'Coats',
           '45' => 'Brushs',
           '5' => 'others',
           '7,8,9' => 'None'
         );

My attempt:

$subFinalFinal = array();

foreach($array as $key => $val){
    if($skey = array_search($val, $subFinalFinal)){ //duplicate value
        $subFinalFinal[$key.','.$skey] = $val;
    } else {
        $subFinalFinal[$key] = $val;
    }

}

But this does not give me the expected result:

Array
(
    [182] => Coats & Jackets
    [211,182] => Coats & Jackets
    [45] => Brushs 
    [5] => others
    [7] => None
    [7,8] => None
    [7,9] => None

)
+4
source share
2 answers

This should work for you:

Just iterate over all the unique values ​​you get with the array_unique()foreach loop. Here is something like this:

Array
(
    [0] => Coats
    [1] => Brushs
    [2] => others
    [3] => None
)

And get all the keys that store this unique value with array_keys(). The tool in this example:

     value     |        key(s)
--------------------------------------
     Coats     |     Array (12, 23)
     Brushs    |     Array (45)
     others    |     Array (5)
     None      |     Array (7, 8, 9)

Then you can implode()put your key array into a string and use it as a key.

code:

<?php

    $array = array('12' => 'Coats', '23' => 'Coats', '45' => 'Brushs', '5' => 'others', '7' => 'None', '8' => 'None', '9' => 'None', );
    $result = [];

    foreach(array_unique($array) as $uniqueValue)
        $result[implode(",", array_keys($array, $uniqueValue))] = $uniqueValue;

    print_r($result);


?>

exit:

Array
(
    [12,23] => Coats
    [45] => Brushs
    [5] => others
    [7,8,9] => None
)
+2

array_flip

$res = array_flip($array);
foreach($res as $k =>$v) $res[$k] = implode(", ", array_keys($array, $k));
print_r(array_flip($res));

:

Array
(
    [12,23] => Coats
    [45] => Brushs
    [5] => others
    [7,8,9] => None
)
+1

Source: https://habr.com/ru/post/1607233/


All Articles