-3

Is there any way to encode a PHP array (or any other similar PHP object) into JSON while having identical keys for a JSON array?

Here is an example:

{"categories" : [ {"key": "data1"}, {"key": "data2"}, {"key": "data3" } ] }

Note that the "categories" object is an array that can be simply parsed with a for loop. However, in PHP, it is impossible it seems to have identical keys in an associative array. So I can't have the structure above as my result from json_encode, and I have to have "key1", "key2", "key3", which prevents me from simply parsing it with a for loop in Javascript.

EDIT: Fixed JSON syntax EDIT2: All data is different. Keys are identical.

20
  • 2
    What you show is not valid JSON. If you want to produce invalid JSON (I cannot think of a reason you might want to do so), you need to write your own encoder/decoder Commented Jul 17, 2014 at 14:27
  • 1
    [] should be {} because only values can be there if there were []'s Commented Jul 17, 2014 at 14:30
  • 2
    just change your json slightly and it should work: {"categories" : [ {"key": "data"},{ "key": "data"},{"key": "data"} ] } Commented Jul 17, 2014 at 14:30
  • 1
    @OzanKurt No, then the last value would overwrite the previous ones. This is simply not valid. Commented Jul 17, 2014 at 14:31
  • 1
    @Jon see JSONLint or similar projects. Short: You can't do that. If you want to use the same key, use an array as it is intended for {"cat":{"key":["item1","item2"]}} Commented Jul 17, 2014 at 14:31

3 Answers 3

1

Use the php json_encode() function to turn a PHP array into a JSON string.

Reversed: json_decode()

Example:

<?php

$json = '{"categories" : { "key1": {"first":"1. value"}, "key2": "data", "key3": "data" } }';

$array = json_decode($json,true);
echo "<pre>";
print_r($array);
echo "</pre>";

Will output:

Array
(
    [categories] => Array
        (
            [key1] => Array
                (
                    [first] => 1. value
                )

            [key2] => data
            [key3] => data
        )

)
0
$array = [
    'categories' => [
        ['key' => 'data'],
        ['key' => 'data'],
        ['key' => 'data']
    ]
];

echo json_encode($array);

That's the same array structure as in your JSON. JSON has the same rules regarding unique keys as PHP does.

(Using PHP 5.4+ array syntax here.)

0
0

Should be straightforward:

echo json_encode([
  'categories' => [
    ['key' => 'data'],
    ['key' => 'data'],
    ['key' => 'data'],
  ],
]);

Also, you can simply reverse engineer the structure by doing:

$str = '{"categories" : [ {"key": "data1"}, {"key": "data2"}, {"key": "data3" } ] }';
$arr = json_decode($str);

var_export($arr);
0

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.