I have the following string:
$string = "[{"006":"BASIC"}, {"007":"ADV"}]";
I need a final array in the form of:
Array(
"006" => BASIC,
"007" => ADV
)
I did it the dirty way as follows:
$string = ltrim($string, "[");
$string = rtrim($string, "]");
$string = explode(",", $string);
$arr1 = json_decode($string[0], true);
$arr2 = json_decode($string[1], true);
$arrFinal = array_merge($arr1, $arr2); //Final Array
Can this be done in a more optimized way?
Also, the original $string can have multiple comma separated segments, and not just two, like below->
$string = "[{"006":"BASIC"}, {"007":"ADV"}, {"008":"ADV"}, {"009":"SUPER"}]";
-
Your initial string is invalid due to having double quotes within double quotes, so that is not your code. If this is actually json, then use json_decode.gview– gview2022年02月25日 05:33:25 +00:00Commented Feb 25, 2022 at 5:33
2 Answers 2
As I noted in the comment to you, your example string is invalid. This example shows a valid string version of json. Use json_decode, with the 2nd parameter set to true to turn the embedded objects into array elements.
You will get an embedded array of arrays, but you can easily flatten that using the spread operator (...) with array_merge.
<?php
$string = '[{"006":"BASIC"},{"007":"ADV"}]';
$r = json_decode($string, true);
$r = array_merge(...$r);
print_r($r);
Outputs:
Array
(
[006] => BASIC
[007] => ADV
)
1 Comment
$string = '[{"006":"BASIC"}, {"007":"ADV"}, {"008":"ADV"}, {"009":"SUPER"}]';
var_dump(json_decode($string, true));
die;
Of if you need to join 2 arrays then you can first decode them and then merge them.
$stringOne = '[{"006":"BASIC"}, {"007":"ADV"}]';
$stringTwo = '[{"008":"ADV"}, {"009":"SUPER"}]';
$finalArray = array_merge(json_decode($stringOne, true), json_decode($stringTwo, true));
var_dump(json_encode($finalArray));
die;