J
J
jasonOk2015-09-23 11:07:41
PHP
jasonOk, 2015-09-23 11:07:41

How to swap keys and values ​​in an array?

array_flip() - swaps keys and values ​​in an array, but if it is array (" a " => 1 , " b " => 1 , "c" => 2) the output will be [ 1 ] => b [2] => c. Those. the value of "a" will disappear.
But I need the values ​​​​with the same keys to be combined and get [ 1 ]=>" a , b ", [2]=>"c"
I think you need to compare the values ​​in the array with each other, and then, if they match, take key using array_keys. But how to implement it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2015-09-23
@jasonOk

$arr = ['a' => 1, 'b' => 2, 'c' => 1, 'd' => 1];
$result = [];

foreach( $arr as $key => $value )
  $result[$value] = isset( $result[$value] ) ? "{$result[$value]},{$key}" : $key;

S
Sergey, 2015-09-23
Protko @Fesor

simple forich to help you:

$source = ['a' => 1, 'b' => 2, 'c' => 1];
$result = [];
foreach ($source as $key => $value) {
    if(array_key_exists($result, $value)) {
        if (is_array($result[$value])) {
             $result[$value][] = $key;
        } else {
             $result[$value] = [$result[$value], $key];
        }
    } else {
        $result[$value] = $key;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question