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

Issue

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?

Solution

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

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