2

I have this PHP array:

$a = array(
  "french"=>"bonjour",
  "italian"=>"buongiorno",
  "spanish"=>"buenos dias"
);

But when I do echo json_encode($a);, I get:

{
   "french": "bonjour",
   "italian": "buongiorno",
   "spanish": "buenos dias"
}

i.e. a JSON object, but I want a JSON array, at the expense of preserving the string keys, like that :

[
   "bonjour",
   "buongiorno",
   "buenos dias"
]

How should I do it?

k0pernikus
  • 60,309
  • 67
  • 216
  • 347
JacopoStanchi
  • 421
  • 5
  • 16

2 Answers2

4

You can use array_values:

echo json_encode(array_values($a));
dave
  • 62,300
  • 5
  • 72
  • 93
1

Php arrays are not "arrays" in the strict sense (collection of string/object/numbers/etc, identified through a numeric index), but are associative arrays. Also know as dictionaries or hash maps. They are for key-value storage.

JSON does not support dictionaries as a type, and hence json_encode transforms these to a json object by design, as objects are supported.

Using json_decode, you can determine by the second parameter if you want a hash map (php array) or an object back:

$a = array(
     "french" => "bonjour",
     "italian" => "buongiorno",
     "spanish" => "buenos dias"
);

$json = json_encode($a);

$object = json_decode($json, false); // this is the default behavior
$array = json_decode($json, true);

var_dump($object); // the object
var_dump($array); // same as the starting array

The object will be:

object(stdClass)#1 (3) {
  ["french"]=>
  string(7) "bonjour"
  ["italian"]=>
  string(10) "buongiorno"
  ["spanish"]=>
  string(11) "buenos dias"
}

And the array will be:

array(3) {
  ["french"]=>
  string(7) "bonjour"
  ["italian"]=>
  string(10) "buongiorno"
  ["spanish"]=>
  string(11) "buenos dias"
}
k0pernikus
  • 60,309
  • 67
  • 216
  • 347
  • Hashing is irrelevant, as it's rather an implementation detail. The term you mean is dictionary, I would say. The distinction in PHP is whether the PHP array has zero-based numeric keys (is thus a "normal" array) or not. The former is encoded as JSON array, the latter as JSON object. – Ulrich Eckhardt Apr 03 '18 at 17:02
  • @UlrichEckhardt The child has different names yet all mean the same thing. My main point is that JSON was never intended to represent php's associative arrays. – k0pernikus Apr 03 '18 at 17:08