How to structure data for JSON with PHP

Asked

Viewed 60 times

0

I have the return of a query that brings me the following items from the following query (OBS : are tables created for examples)

 select * from alunos a left join financs f on f.aluno_id = a.id left join financ_detalhes fd on fd.financ_id = f.id

inserir a descrição da imagem aqui

What I want to do is structure this for json from php to look like this:

{
  "aluno": [
    {
      "id": "1",
      "nome": "felipe",
      "nr_cpf": "11111",
      "situação": "A",
      "financeiro": [
        {
          "id": "1",
          "dt_pag": "2018-04-10",
          "situacao": "p",
          "descricao": [
            {
              "id": "1",
              "descricao": "olá chefe"
            },
            {
              "id": "2",
              "descricao": "olá jurubeba"
            }
          ]
        },
        {
          "id": "2",
          "dt_pag": "2018-04-10",
          "situacao": "p",
          "descricao": []
        }
      ]
    },
    {
      "id": "2",
      "nome": "jose",
      "nr_cpf": "2222",
      "situação": "A",
      "financeiro": [
        {
          "id": "1",
          "dt_pag": "2018-04-10",
          "situacao": "p",
          "descricao": []
        }
      ]
    }
  ]
}

I’ve tried every possible way but I can’t, does anyone have any tips or know how I can do it?

Moment I gave up temporarily:

 foreach($alunosBase as $index=>$aluno) {

   $financeiroDesc[$index][] = ['detalhes_id' => $aluno['detalhes_id'],'detalhes_descricao' => $aluno['detalhes_descricao']];

    if(!in_array($aluno['id_financ'],$mapRegFinan)) {
       $financeiro[$index][] = ['id_financ' => $aluno['id_financ'], 'dt_pag'=> $aluno['dt_pag']];
       $mapRegFinan['id_financ'] = $aluno['id_financ'];
    }

}
  • I didn’t quite understand your question, but if you want to turn everything into JSON just use the function json_encode() and then display it on the screen.

  • Opa...yes this is true only if I directly apply json_encode the return will be the same as the image in the link -> https://1drv.ms/u/s! Asjhc3mhfsggaqytqskfyi58dn4 the result is two record repeating changing only the description table record, it is because it is a Join Inner. I believe it would be right to look like this in the image->https://1drv.ms/u/s! Asjhc3mhfsggaxvlcaxmyjrz6qi

  • If using PDO use Pdostatement::fetchObject, if using mysqli use mysqli_fetch_object to fetch the database data, then use var_dump to print on the screen and post in the question the result

No answers

Browser other questions tagged

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