1
\$\begingroup\$

I have an associative array:

$input = [
    ['key'=>'x', 'value'=>'a'],
    ['key'=>'x', 'value'=>'b'],
    ['key'=>'x', 'value'=>'c'],
    ['key'=>'y', 'value'=>'d'],
    ['key'=>'y', 'value'=>'e'],
    ['key'=>'z', 'value'=>'f'],
    ['key'=>'m', 'value'=>'n'],
];

And I want to reform it simple in:

$output = [
    'x'=>['a','b','c'],
    'y'=>['d','e'],
    'x'=>'f',
    'm'=>'n'
]

So basically, conditions are:

  1. If same key found then put values in an array.
  2. If no same key found then value remains string.

You can replace associative array with object if you are more comfortable with objects.

Here is my working solution for this problem:

foreach($input as $in){
    if(!empty($output[$in['key']])){
        if(is_array($output[$in['key']])){
            $output[$in['key']][] = $in['value'];
            continue;
        }
        $output[$in['key']] = [$output[$in['key']],$in['value']];
        continue;
    }
    $output[$in['key']] = $in['value'];
}      
print_r($output);

However I believe that it can be done in much compact and efficient way. Please comment your answers if someone has better solution. Your help is much appreciated!

\$\endgroup\$
  • 1
    \$\begingroup\$ Your question has already been answered on Stack Overflow. Do you still want an answer here? \$\endgroup\$ – Mast Jan 15 '18 at 15:33
  • \$\begingroup\$ Silly me, I had missed that you had a "working" solution and basically posted the same thing as an example. Duh! Where's my coffee? ;) \$\endgroup\$ – A Smith Jan 16 '18 at 11:40
  • \$\begingroup\$ :) funny..and yes it has been answered on other site, so I am good. I don't need an answer anymore. I don't know how to close the question here. \$\endgroup\$ – Learner Jan 18 '18 at 8:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.