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


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:

    [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>";

But is there any other ways to solve this?


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


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

Answered By – Anant – Alive to die

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published