1

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?

2
  • 1
    this is not valid json in your string. did you try unserialize? php.net/manual/en/function.unserialize.php Commented Oct 3, 2022 at 3:31
  • 2
    Unserialize the $string will cause an error. This is the error: unserialize(): Error at offset 0 of 65 bytes Commented Oct 3, 2022 at 3:37

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much haha, didn't realize i made such a small mistake
No, problem, happens to all at the beginning

Your Answer

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.