Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
1  
If you are creating json yourself then your json is wrong – dreamCoder Apr 15 at 7:11
@dreamCoder: Thanks, That was it. – Amyth Apr 15 at 7:13

3 Answers

up vote 8 down vote accepted

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
    )

)
share|improve this answer
2  
Using str_replace(): $str = "{'Codes': ['01239EEF', '01240EDF'], 'Done' : ['1', '0']}"; $array = json_decode(str_replace("'", '"', $str), true); print_r($array); – HamZa DzCyberDeV Apr 15 at 7:11
@mohammadmohsenipur: Thanks, that was it. – Amyth Apr 15 at 7:13

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

share|improve this answer

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"
  }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.