Manipulation of JSON

Asked

Viewed 69 times

0

I have the following code:

$Json = array();

foreach ($Dados as $ln){
    $Json[label] = $ln['NOME'];
    $Json[value] = $ln['EMAIL'];            
}

echo json_encode($Json);

With this I have the following return:

{"label":"xxxxxxxxx","value":"xxxxxxxxxxx"}

I would like to bring all returns from the bank and also remove quotes from both label and value.

Expected result:

[
  {label:"xxxxxxxxx",value:"xxxxxxxxxxx"}
  {label:"yyyyyyyyy",value:"yyyyyyyyyyy"}
  {label:"zzzzzzzzz",value:"zzzzzzzzzzz"}
]
  • Only returns a pq vc overrides the array at each foreach iteration ...

1 answer

2


You can solve this by creating an Indice variable to group the label and value.

$Json = array();
$i = 0;
foreach ($Dados as $ln){
    $Json[$i]['label'] = $ln['NOME'];
    $Json[$i]['value'] = $ln['EMAIL'];            
    $i++;
}

echo json_encode($Json);

Depending on the case just assign the current item to a new position of the array resolves:

foreach ($Dados as $ln){
    $Json[] = $ln;
}
echo json_encode($Json);
  • Thank you @rray , worked perfectly.

Browser other questions tagged

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