使用非数字键将PHP数组编码到JSON数组

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?

You can use array_values:

echo json_encode(array_values($a));

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"
}