Json Encoding Issue in PHP 5
I'm trying to use Json with my database using php5 but suffering from a weird result. This database has four fields - 'id', 'Title', 'Thread', 'date' but the jason result looks like the following.
[
{
"0": "1",
"id": "1",
"1": "Title 1",
"Title": "Title 1",
"2": "Thread 1",
"Thread": "Thread 1",
"3": "2011-10-19",
"date": "2011-10-19"
},
{
"0": "2",
"id": "2",
"1": "Title 2",
"Title": "Title 2",
"2": "Thread 2",
"Thread": "Thread 2",
"3": "2011-10-03",
"date": "2011-10-03"
}
]
You can see there are duplicated information in the result. Where are they from?? I will attach the code I've written... Jason & PHP masters, please enlighten me :'(.. Thank开发者_如何学C you in advance.. I will try to solve it again as I wait for your help....
private static function queryAndFetch($tableName)
{
$query = "SELECT id, Title, Thread, date From $tableName";
$result = mysqli_query(self::$link, $query);
if(!($result))
{
echo "Error";
exit;
}
// $posts = mysqli_fetch_assoc(self::$result); - Working
self::$fetchedResult = array();
while($row = mysqli_fetch_array($result))
{
self::$fetchedResult[] = $row;
}
}
private static function encode()
{
//print_r(self::$fetchedResult);
//if($format == 'json') {
header('Content-type: application/json');
echo json_encode(self::$fetchedResult);
//}
//echo "hi".json_last_error();
}
}
mysqli_fetch_array
returns the result rows with both associative and enumerated keys. If you only want the associative array keys, then use mysqli_fetch_assoc
.
It looks like your mysqli_fetch_array($result) is returning an associative array rather than indexed array.
Try this change:
while($row = mysqli_fetch_array($result)) {
self::$fetchedResult[] = array(
'id' => $row->id,
'Title' => $row->Title,
'Thread' => $row->Thread,
'date' => $row->date
);
}
If that doesn't work, try using $row['id'], $row['Title'], $row['Thread'] and $row['date'].
Alternatively, to avoid having to write out each field, change to mysqli_fetch_assoc($result) specifically.
I suspect this is the issue you've got?
Thanks, MyStream
精彩评论