1

I have the following JSON array:

{"key1":"Example1","key2":"Example2","key3":"Example3","key4":"Example4","key1":"Example5","key2":"Example6","key3":"Example7","key4":"Example8","key1":"Example9","key2":"Example10","key3":"Example11","key4":"Example12"}

Using PHP is it possible to display a specific recurring value, for example if I wanted to display "key1" in a foreach loop it would return the following:

Example1
Example5
Example9

Appreciate any tips on what to use to do this, thanks.

The Bobster
  • 573
  • 4
  • 20
  • 1
    You are using duplicate keys in your JSON. Please check http://stackoverflow.com/questions/21832701/does-json-syntax-allow-duplicate-keys-in-an-object – mario.van.zadel Sep 21 '15 at 10:54
  • Thanks for the reply - if you're not allowed to use duplicate keys do you know what the best way to save and output a recurring set of values would be like "Name", "Age", "Gender", "Name", "Age", "Gender", etc? – The Bobster Sep 21 '15 at 11:22
  • You should use arrays: `{"key1": ["Example1", "Example5", "Example9"], "key2": ["Example2","Example6""Example10"], ...}` – mario.van.zadel Sep 22 '15 at 05:14

1 Answers1

2

You aren't going to be able to do this using json_encode because it's not valid JSON. (Keyspace collision)

You are going to need to assemble the object manually.

You might consider creating the individual items, then using implode(). Then you can prepend and append { and }.

<?php
$jsonObject='{"key1":"Example1","key2":"Example2","key3":"Example3","key4":"Example4","key1":"Example5","key2":"Example6","key3":"Example7","key4":"Example8","key1":"Example9","key2":"Example10","key3":"Example11","key4":"Example12"}';

$jsonArray = array_map(
    function($array){
    $keyValue=explode(":",$array);
    return array("key"=>substr($keyValue[0],1,-1),"value"=>substr($keyValue[1],1,-1));

    },
    explode(
        ",",
        substr($jsonObject,1,-1)

    )
);

foreach($jsonArray as $object){
    $output[$object['key']][]=$object['value']; 
}
echo implode("\n",$output['key1']);

?>
Vahid Moradi
  • 791
  • 7
  • 16