1

I have a string that when I var_dump returns the following

string(20) "{\"key1\":\"key1_value",\"key2\":\"key2_value\"}"

How can I convert that into an array that will return the following when I var_dump?

array(2) { ["key1"]=>  string(20) "key1_value" ["key2"]=>  string(20) "key2_value" } 

Thanks,
Tee

4 Answers 4

8

It looks like a simple JSON array that got mangled by PHP's magic_quotes or some other escaping function. Turn off magic_quotes and run json_decode() on the string.

// If you cannot disable `magic_quotes` or you escaped it manually, use this
$array = json_decode(stripslashes($strings), true);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Sander, that works. I was just doing json_decode without the stripslases which was the issue. Also I actually needs to convert that into an array since what you recommended returned an StdObject. So actual code I used is (array) json_decode(stripslashes($strings));
Actually what David L.-Pratte recommends by setting second parameter to true in the json_decode works too. So json_decode(stripslashes($strings), true);
Ah, yes. Of course. I have edited my answer for future reference.
7

What you have as data looks like valid JSON. You probably can use json_decode with the second parameter to true (to get an associative array) like this:

$array = json_decode($string, true);

Comments

0

The explode function will get you what you need.

Comments

0
explode(',\\',$string); 

should do the trick.

1 Comment

He needs explode. implode turns an array into a string.

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.