Answer the question
In order to leave comments, you need to log in
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>');
Array
(
[a] => 4
[b] => 2
[c] => 3
)
Array
(
[a] => 5
[b] => 2
[c] => 3
)
Answer the question
In order to leave comments, you need to log in
$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>');
$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 questionAsk a Question
731 491 924 answers to any question