Reputation: 2244
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.
Upvotes: 3
Views: 76
Reputation: 837
Create your array like this
$i=0;
while($rows = mysql_fetch_array($filter)) {
$result[$i]['name'] = $rows['name'];
$result[$i]['id'] = $rows['id'];
$i++;
}
$res = json_encode($result);
print_r($res);
It will return output result
Upvotes: 0
Reputation: 2928
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);
Upvotes: 2
Reputation: 1920
Try this
$result = array();
while ($rows = mysql_fetch_assoc($filter)) {
$result[] = $rows;
}
echo json_encode($result);
Upvotes: 2