Home > Blockchain >  PHP String(which contain array of object) to Array conversion
PHP String(which contain array of object) to Array conversion

Time:10-03

Suppose I have a string (which contain array of objects):

$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";

My goals is to get the output to look like this when I print_r:

Array
(
    [0] => Array
        (
            [test] => 1
            [anothertest] => 2
        )

    [1] => Array
        (
            [test] => 3
            [anothertest] => 4
        )

)

I tried to json_decode($string) but it returned NULL

Also tried my own workaround which is kinda solved the problem,

$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
$string = substr($string, 1, -1);
$string = str_replace("'","\"", $string);
$string = str_replace("},","}VerySpecialSeparator", $string);
$arrayOfString = explode("VerySpecialSeparator",$string);
$results = [];
    
foreach($arrayOfString as $string) {
    $results[] = json_decode($string, true);
}

echo "<pre>";
print_r($results);
die;

But is there any other ways to solve this?

CodePudding user response:

As per your given data, if quotes will be corrected, then you will get your desired output, so get it done like below:

<?php

$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
$string = str_replace("'",'"', $string);
print_r(json_decode($string,true));

https://3v4l.org/PDI7O

  • Related