Ho bisogno di convertire un array PHP in JSON ma non ottengo quello che mi aspetto. Voglio che sia un oggetto che posso navigare facilmente con un indice numerico. Ecco un esempio di codice:PHP Array to Json Object
$json = array();
$ip = "192.168.0.1";
$port = "2016";
array_push($json, ["ip" => $ip, "port" => $port]);
$json = json_encode($json, JSON_PRETTY_PRINT);
// ----- json_decode($json)["ip"] should be "192.168.0.1" ----
echo $json;
Questo è ciò che ottengo
[
[
"ip" => "192.168.0.1",
"port" => "2016"
]
]
ma voglio ottenere un oggetto invece di matrice:
{
"0": {
"ip": "192.168.0.1",
"port": "2016"
}
}
Grazie :)
* Perché * vuoi che l'array esterno diventi un oggetto JSON? Se ha solo i tasti numerici, un array fornisce le stesse informazioni in uno spazio leggermente inferiore ed è più facile lavorare con il lato JS delle cose (puoi usare 'Array :: forEach' e' Array :: map' per esempio). – 00dani
@ 00Davo Grazie, perché ho pensato che fosse più semplice gestirlo quando si tratta di un oggetto hhh, e lo uso principalmente solo sul lato server (PHP) :) P.S. Upvoted –