Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json showing duplicate output of mysql result

Tags:

json

php

I am trying to print json_encode and I get output duplicated. I am certain there is one single record in database and yet it shows the same record data twice in various format. This is it:

[{"0":"Polo","name":"Polo","1":"City ","location":"City ","2":"Manama","city":"Manama"}]

The code behind this is:

$dataArray = array();
while($r = mysql_fetch_array($result))
{
    $dataArray[] = $r;
}

print json_encode($dataArray, JSON_UNESCAPED_UNICODE);

Any idea?

like image 796
sys_debug Avatar asked Jan 17 '26 16:01

sys_debug


1 Answers

This is because the default behavior of mysql_fetch_array() is to return both a column name and index keyed array.

Use mysql_fetch_assoc() or set the second parameter of mysql_fetch_array().

while($r = mysql_fetch_assoc($result)) {
    $dataArray[] = $r;
}
like image 149
Jason McCreary Avatar answered Jan 20 '26 09:01

Jason McCreary



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!