Doubt PHP Json Array

Asked

Viewed 41 times

-1

In the query below

$id_candidato = 1;
$id_vaga = 2; 

$sql = $mysqli->query("SELECT * FROM candidatos WHERE id_vaga = '".$id_vaga."' AND id_candidato = '".$id_candidato."'");

if($sql->num_rows > 0){
    while($row = $sql->fetch_array(MYSQLI_BOTH)){
        $registro = array(
            "ID" => $row['id'],
            "VAGA" => $row['id_vaga'],
            "ID_CANDIDATO" => $row['id_candidato']
        );

        $retorno[] = $registro;

    }
    $mysqli->close();
    $retorno = json_encode($retorno);
    echo $retorno;

}else {
    echo "nao existe";
}

I get the following return:

[{"ID":"1","VAGA":"2","ID_CANDIDATO":"1"},{"ID":"2","VAGA":"2","ID_CANDIDATO":"1"}]

My question is how do I get the return displayed in the mode below?

[{"ID":"1","VAGA":"2","ID_CANDIDATO":"1", "ID":"2","VAGA":"2","ID_CANDIDATO":"1"}]
  • Dude, can you explain the need for this? Because, I haven’t seen any json in this format yet. Encode ai takes an array and returns the data set as it received from the array.

  • @Henriquesantiago opa, I need to get VAGUE in the same index in the answer of Brazilian Portuguese. Ex: var resposta = Sponse.data[0]. VAGA;

  • And what’s wrong with having var resposta = response.data[0].VAGA and also var resposta = response.data[1].VAGA? Multiple fields with the same name within the same JSON object is not something javascript will be able to interpret correctly in any way.

  • but in case, you would only have a record with repeated fields... {"ID":"1","ID":"2"}, look, how would a record with two equal fields?

  • you guarantee that you are sending this data set to this variable dataat the angle of the correct shape?

  • gives a threshing to check

  • It’s all right. I need to store in a $Cope just to do the foreach

  • @Henriquesantiago Researching realized that it works with nested arrays. If you want to improve my answer feel free. Thanks for your attention.

Show 3 more comments

1 answer

0


Well, I realized that by making nested arrays I can make the loop properly in the Angularjs. I don’t know if it’s the best way to write the script:

$id_candidato = 1;
$id_vaga = 2; 

$sql = $mysqli->query("SELECT * FROM candidatos WHERE id_vaga = '".$id_vaga."' AND id_candidato = '".$id_candidato."'");

if($sql->num_rows > 0){
  while($row = $sql->fetch_array(MYSQLI_BOTH)){
    $registro = array(
        "ID" => $row['id'],
        "VAGA" => [$row['id_vaga']],
        "ID_CANDIDATO" => $row['id_candidato']
    );

    $retorno[] = $registro;

}
  $mysqli->close();
  $retorno = json_encode($retorno);
  echo $retorno;

}else {
  echo "nao existe";
}

that brings me as a result

[{"ID":"1","VAGA":["2"],"ID_CANDIDATO":"1"},{"ID":"2","VAGA":["2"],"ID_CANDIDATO":"1"}]

Browser other questions tagged

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