Create JSON from Select from the database

Asked

Viewed 556 times

1

I populated a mysql database with data in this format: inserir a descrição da imagem aqui 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:

inserir a descrição da imagem aqui

 $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.

1 answer

1


Hello.

Use the state as the array key.

$resultado = $this->sql->select("SELECT * FROM tb_unidades");


$estados = array();
foreach ($resultado as $row) {

    $estados[$row["estado"]][$row["cidade"]][] = $row;
}

Gives a print_r in this array and see how it looks.

  • 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?

  • So, but with only 1 array you get all this.

  • checks my Edit, I thought, I thought cities would come in as a new array, but actually mixed it all up

  • What’s strange because when I print only $cities, it returns me correctly

  • 1

    Look at the Edit I did in the answer

  • Exactly that, thank you

  • worked out? if it is the case, add 1 more key to the neighborhood, I believe it will get better.

  • For my application do not think necessary, is a combo box city and state

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.