2

I am looking to convert the following string to a PHP Array:

{ 'Codes': ['01239EEF', '01240EDF'], 'Done' : ['1', '0'] }

I am trying to convert this to an Array that looks something like the following:

{[Codes] => {[0] => '01239EEF', [1] => '01240EDF'}, [Done] => {[0] => '1', [1] => '0'}}

I tried using json_decode with Array argument explicitly set to true. But it always returns NULL for some reason.

1
  • 1
    If you are creating json yourself then your json is wrong Commented Apr 15, 2013 at 7:11

3 Answers 3

8

problem is on json use " instead of '

 { 'Codes': ['01239EEF', '01240EDF'], 'Done' : ['1', '0'] }

must be

 { "Codes": ["01239EEF", "01240EDF"], "Done" : ["1", "0"] }

output with json_decode

 stdClass Object
(
   [Codes] => Array
    (
        [0] => 01239EEF
        [1] => 01240EDF
    )

    [Done] => Array
    (
        [0] => 1
        [1] => 0
    )

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

1 Comment

Using str_replace(): $str = "{'Codes': ['01239EEF', '01240EDF'], 'Done' : ['1', '0']}"; $array = json_decode(str_replace("'", '"', $str), true); print_r($array);
0

You can use str_replace(',",$string) and then json_encode

Comments

0

The name and value must be enclosed in double quotes

single quotes are not valid in json_decode function

please change your string like

$js_str = '{ "Codes": ["01239EEF", "01240EDF"], "Done" : ["1", "0"] }';

and your output will be like

object(stdClass)#1 (2) {
   ["Codes"]=>
  array(2) {
    [0]=>
    string(8) "01239EEF"
    [1]=>
    string(8) "01240EDF"
  }
  ["Done"]=>
  array(2) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "0"
  }
}

Comments

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.