remove [] from the array list

Asked

Viewed 52 times

0

i have a php file that generates a json in array for another application to read, however everything is working but the json is coming with the [] of the list, and my application can only read from {}, have to remove before generating the json as [] ?

Code that generates json

<?php

$result = $con->query($Sql_Query);

$rows = [];

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


    array_push($rows, $row);

}
<br>
$json = json_encode($rows);
<br>
$file = 'file.json';
<br>
file_put_contents($file, $json);
<br>
 mysqli_close($con);
<br>
?>

Result of json

[{"ID":"10","name":"name","email":"[email protected]","id_user":"12345"}]
  • 1

    if it is an array will always come with [], with {} only if it is a single object, I think you need to change your application that reads, because it is expecting a single object

1 answer

0


Checks whether the result of mysqli_fetch_assoc has more than one element, if you have more than one element does the flow that was already happening, if not, assigns the first and only element in the variable $rows

<?php

$result = $con->query($Sql_Query);

$rows = [];

if(count(mysqli_fetch_assoc($result)) > 1){

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

        array_push($rows, $row);

    }

} else {

    $rows = array_shift(mysqli_fetch_assoc($result));

}

<br>
$json = json_encode($rows);
<br>
$file = 'file.json';
<br>
file_put_contents($file, $json);
<br>
 mysqli_close($con);
<br>
?>

Browser other questions tagged

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