Problem with Array for Json

Asked

Viewed 60 times

0

I made a simple request to the database and am trying to pass this data to a json but a part is being duplicated in JSON

PHP:

$query = "SELECT * FROM UNIFORMS";

$result = mysqli_query($connection,$query);

$rows= array();

while($sonuc = mysqli_fetch_assoc($result)) {

    $rows[id]=$sonuc[id];
    $rows[userid]=$sonuc[userid];
    $rows[uniform_type]=$sonuc[uniform_type];
    $rows[date]=$sonuc[date];
    $rows[size]=$sonuc[model];
    $rows[color]=$sonuc[color];
    $rows[provider_id]=$sonuc[provider_id];
    $rows[contract]=$sonuc[contract];
    $rows[amount]=$sonuc[amount];
    $rows[cost]=$sonuc[cost];
    $rows[place]=$sonuc[place];

    array_push($rows,$sonuc);
}

 echo json_encode($rows);

Answer:

{…}0: Object { id: "30", userid: "YS3ul395jBDcBf8I", uniform_type: "Blazer", … }1: Object { id: "31", userid: "YS3ul395jBDcBf8I", uniform_type: "Blazer", … }2: Object { id: "32", userid: "YS3ul395jBDcBf8I", uniform_type: "Blazer", … }3: Object { id: "33", userid: "YS3ul395jBDcBf8I", uniform_type: "Blazer", … }amount: "10"color: "Preto"contract: "INCA"cost: "50"date: "2018-01-26 15:00:57"id: "33"place: "Nit"provider_id: "1"size: "1/2 Sem Gola"uniform_type: "Blazer"userid: "YS3ul395jBDcBf8I"__proto__: Object { … } uniform.php:307:13

Note that Object 33 is duplicated

inserir a descrição da imagem aqui

1 answer

1

To the following lines:

$rows[id]=$sonuc[id];
$rows[userid]=$sonuc[userid];
$rows[uniform_type]=$sonuc[uniform_type];
$rows[date]=$sonuc[date];
$rows[size]=$sonuc[model];
$rows[color]=$sonuc[color];
$rows[provider_id]=$sonuc[provider_id];
$rows[contract]=$sonuc[contract];
$rows[amount]=$sonuc[amount];
$rows[cost]=$sonuc[cost];
$rows[place]=$sonuc[place];

Assigning associative values in the array rows and the line:

array_push($rows,$sonuc);

Assigns indexed values to the array rows.

I assume the second option is your goal, since the first option will override the previous value assigned to the array rows with each iteration; and so you only see the 33 "repeated" as it is the last item on your list.

To solve your problem just remove the lines that assign associative values:

while($sonuc = mysqli_fetch_assoc($result)) {
    array_push($rows,$sonuc);
}

Browser other questions tagged

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