1

i want return my data from mysql to json array with do while loop. when i return one record with json it is well. but i want return list of array in one json array. how can do that with index in while? my code have error and i don't know how can do it. with one record it is well but more can't.

 $json="array(";
  do{
    $json=."'$row_query['id']'=>array('fname'=>$row_query['fname'],'lname'=>$row_query['lname']),";

 } while ($row_query = mysqli_fetch_assoc($query));
 json=.")";
echo json_encode($json,JSON_UNESCAPED_UNICODE);
1
  • The do-while loop is incorrect - in the first iteration, there's no $row_query, as this var is set after the first iteration Commented Nov 12, 2017 at 10:07

2 Answers 2

4

There's no need to add quotes, brackets, parentheses or whatever. json_encode function will do it for you. Just provide an array to it:

$json = [];
while ($row_query = mysqli_fetch_assoc($query)) {
    $json[$row_query['id']] = [
        'fname'=>$row_query['fname'],
        'lname'=>$row_query['lname'],
    ];
}
echo json_encode($json,JSON_UNESCAPED_UNICODE);
Sign up to request clarification or add additional context in comments.

Comments

1

This is the most super easy version. You may try this.

$json = new array();
do{
array_push($json,$row_query);
} while ($row_query = mysqli_fetch_assoc($query));

or

$json = [];
do{
 $json[] = $row_query;
} while ($row_query = mysqli_fetch_assoc($query));

Atlast encode your json variable.

$json = json_encode($json);
echo $json;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.