The problem of converting php arrays to json

<?php
$a = [
    "name",
    "age"
];
var_dump( json_encode($a));

the result is"["name", "age"]"
this is a json data is fine, but what is returned is a json collection and what I need is a json object, I expect the following result

"{"name", "age"}",

my solution now is to change my code as follows

$a = [
    "name" => 1,
    "age" => 1
];
var_dump( json_encode($a));

that is, to change the array into a key-value pair, each key has the same value of 1, which is useless. The result is as follows:
"{"name": 1, "age": 1}"
this can meet my needs, but personally, this is a bit too low. I don"t know if there is a good way

.
Mar.07,2021

'{"name", "age"}' is not json,. If it is an object, it must be a key-value pair. In json, the array is represented by


clipboard.png


whether it is returned to the foreground or used in the background, and the foreground does not need to operate. Just use json_encode ($a)
if you are using the json object yourself in the background, you can use json_decode (json_encode ($a)) is a json object)

Menu