Home > Mobile >  Convert particular String to Array in PHP
Convert particular String to Array in PHP

Time:02-25

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"}]";

CodePudding user response:

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
)

CodePudding user response:

    $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;
  • Related