Problem with Array for Json

0

I made a simple request to the database and I'm 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

Notice that Object 33 is duplicated

    
asked by anonymous 26.01.2018 / 18:51

1 answer

1

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];

You are assigning associative values in the array rows and the line:

array_push($rows,$sonuc);

Assigns indexed values in array rows .

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

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

while($sonuc = mysqli_fetch_assoc($result)) {
    array_push($rows,$sonuc);
}
    
26.01.2018 / 18:57