Reputation: 4460
I'm trying create a JSON Array using PHP. But I want this JSON receive a master key like this: cidades:[{"id":"1", "nome":"Guaira"}]
and when I try create its only create [{"id":"1","cidade":"Guaira"}]
.
How can I do it ?
<?php
include '../objetos/Cidade.php';
include '../dao/CidadeDAO.php';
if($_GET['action'] == 'getCidades'){
$idEstado = $_GET['idEstado'];
$dao = new CidadeDAO();
$lista = $dao->getCidadeByEstado($idEstado);
$arr = array();
foreach ($lista as $object){
$result = array("id" => $object['id'], "cidade" => $object['cidade']);
array_push($arr, $result);
}
echo json_encode($arr);
//output: [{"id":"1","cidade":"Guaira"},{"id":"1","cidade":"Barretos"}] }
?>
Upvotes: 0
Views: 53
Reputation: 67
Try this:
$arr["cidades"] = array();
array_push($arr["cidades"], $result);
This code produces a JSON formatted data with a key named "cidades" attached to it so that something like cidades:[{"id":"1", "nome":"Guaira"}]
is produced. For clarity check out this.
Upvotes: 1
Reputation: 91
Create a top-level array with key 'cidades'
and put your data into :
$arr = array('cidades' => array());
foreach ($lista as $object){
$result = array("id" => $object['id'], "cidade" => $object['cidade']);
array_push($arr['cidades'], $result);
}
Upvotes: 2