1

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"}]";
gguney
2,6711 gold badge17 silver badges30 bronze badges
asked Feb 25, 2022 at 5:30
1
  • 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. Commented Feb 25, 2022 at 5:33

2 Answers 2

3

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
)
answered Feb 25, 2022 at 5:35

1 Comment

This makes sense. I'll try to get the string in the correct format and then use json_decode with the true param. Actually I'm already using that further down in my code.
1
 $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;
answered Feb 25, 2022 at 5:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.