1
I populated a mysql database with data in this format: and wanted to return this in json using php, the problem is that I have for example several lines with the same state, and need to return the json enste format:
{
"Estados": {
"Espirito Santo": {
"Cidades": {
"Cidade 1": {
"Nome Unidade": {
"Nome": "a",
"Endereco": "b",
"log": "222",
"lat": "111"
},
"Nome Unidade2": {
"Nome": "a",
"Endereco": "b",
"log": "222",
"lat": "111"
}
}
}
}
}
}
That is, group all the repeated states, cities as well. I have no idea how to do, what I got so far was to remove the id and create the array with the states ( repeated) like this:
$resultado = $this->sql->select("SELECT * FROM tb_unidades");
//print_r($resultado);
//print_r($resultado['0']['estado']);
$estados = array();
foreach ($resultado as &$row) {
unset($row['id']);
$estados[] = array($row['estado']);
}
$estados = array("Estados"=>$estados, "Ben"=>"37", "Joe"=>"43");
print_r(json_encode($estados));
EDIT: Trying the proposed solution I obtained this:
$resultado = $this->sql->select("SELECT * FROM tb_unidades");
$estados = array();
$cidades = array();
foreach ($resultado as $row) {
$cidades[$row["cidade"]][] = $row;
$estados[$row["estado"]][] = $cidades;
}
$estadosp = array("Estados"=>$estados);
return json_encode($estadosp);
The cities were repeated, and appeared some from other states.
I managed to create the 2 array of states and cities without repeating, ok, but now how do I put the city inside the states array?
– Igor Oliveira
So, but with only 1 array you get all this.
– VMCO
checks my Edit, I thought, I thought cities would come in as a new array, but actually mixed it all up
– Igor Oliveira
What’s strange because when I print only $cities, it returns me correctly
– Igor Oliveira
Look at the Edit I did in the answer
– VMCO
Exactly that, thank you
– Igor Oliveira
worked out? if it is the case, add 1 more key to the neighborhood, I believe it will get better.
– VMCO
For my application do not think necessary, is a combo box city and state
– Igor Oliveira