M
M
Mikhail Fedotov2017-11-18 19:11:19
PHP
Mikhail Fedotov, 2017-11-18 19:11:19

How to convert complex string to associative array?

I need to convert a complex string into a simple associative array.
Here is the code that works, but is not to my liking:

$string = 'a:1|b:2|c:3|a:4';
        $array1 = array();
        $array2 = explode('|', $string);
        foreach($array2 as $str) {
            list($key, $value) = explode(':', $str);
            $array1[$key] = $value;
        }
        echo('<pre>');
        print_r($array1);
        echo('</pre>');

Here we see that "a" is repeated twice and, of course, replaced by the last value. In the output I get:
Array
(
    [a] => 4
    [b] => 2
    [c] => 3
)

But I need to make it so that the same keys add up. So the output should be:
Array
(
    [a] => 5
    [b] => 2
    [c] => 3
)

How to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya, 2017-11-18
@Libiros

$string = 'a:1|b:2|c:3|a:4';
$array1 = array();
$array2 = explode('|', $string);
foreach($array2 as $str) {
  list($key, $value) = explode(':', $str);
  $array1[$key] = array_key_exists($key, $array1) ? $array1[$key] + $value : $value;
}
echo('<pre>');
print_r($array1);
echo('</pre>');

S
Slava Vitrenko, 2017-11-20
@mxuser

$string = 'a:1|b:2|c:3|a:4';
        $array1 = array();
        $array2 = explode('|', $string);
        foreach($array2 as $str) {
            list($key, $value) = explode(':', $str);
            $array1[] = [$key => $value];
        }
        echo('<pre>');
        print_r($array1);
        echo('</pre>');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question