Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to covert php data into json format?

Tags:

json

php

Here i am fetching data using php code.But i want the same code to be convert into json format.I am not getting the way to do it. I have tried it in this way.

my code

 while ($rows = mysql_fetch_array($filter)) {
        $result['name'] = $rows['name'];
        $result['id'] = $rows['id'];
    }
  $res = json_encode($result);
    print_r($res);

getting result

{"name":["sradha","nicky","demo","testing"],"id":["1","2","3","4"]}

Here i want it in this below json format

  [{id:1, name:'sradha'},
    {id:2, name:'nicky'},
    {id:3, name:'demo'},
    {id:3, name:'testing'}];

Please suggest me. Any suggestion will highly appreciate. Thank you in advance.

like image 648
sradha Avatar asked Jul 22 '26 14:07

sradha


1 Answers

Try below:

while ($rows = mysql_fetch_assoc($filter)) {
    $result['name'] = $rows['name'];
    $result['id'] = $rows['id'];
    $new_result[] = $result;
}

$res = json_encode($new_result);
print_r($res);

OR

while ($rows = mysql_fetch_assoc($filter)) {
    $result[] = $rows;
}

$res = json_encode($result);
print_r($res);
like image 151
Kausha Mehta Avatar answered Jul 24 '26 05:07

Kausha Mehta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!