1

I have below string. I need to convert this to an associative array. The string which I am getting, as a result, is coming from ajax and for this format of string I didn't find any solutions.

$string= '[{"name":"title","value":"%post_title%"},{"name":"author","value":"%author_name%"}]';

I need to convert the above string to an associative array so that I can use that array in foreach.

Bhavya Hegde
  • 172
  • 1
  • 11
  • 3
    That is a JSON String so use `$array = json_decode($string,1);` [The manual](http://php.net/manual/en/function.json-decode.php) – RiggsFolly Oct 13 '18 at 09:28
  • I did not find any solutions given for this format of the string. I found the same question, but the format of the string was different there. @RiggsFolly – Bhavya Hegde Oct 13 '18 at 09:37
  • Check the [json.org site](http://json.org/) to familiarize yourself with what JSON looks like. It is used for many things nowadays – RiggsFolly Oct 13 '18 at 09:39

1 Answers1

5

Use json_decode with second parameter set to true, in order to convert your input JSON format string to an associative array.

$string= '[{"name":"title","value":"%post_title%"},{"name":"author","value":"%author_name%"}]';

// convert the JSON format to array
$output_array = json_decode($string, true);

// print to check output
echo "<pre>"; print_r($output_array); echo "</pre>";
Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57