PHP:MY​​SQL数组到JSON停止重复?

时间:2018-03-09 17:34:17

标签: php mysql json

因此,每当我从我的mysql数据库下载数据,并通过PHP转换为JSON数组然后显示它,我就会得到重复的值。

我明白为什么会这样,但有没有办法删除数字副本?:/

{"id":"1","0":"1","userId":"23","1":"23","message":"HELLO","2":HELLO"},
{"id":"2","0":"2","userId":"53","1":"53","message":"WOW","2":WOW"}

2 个答案:

答案 0 :(得分:1)

对于PDO,在查询执行后使用PDO::FETCH_ASSOC标志

$sth = $dbh->prepare("SELECT col FROM table");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);

对于mysql_ *函数:

$query = "SELECT col FROM table";
$result = mysqli_query($connection, $query);
$output = array();
while($row = mysqli_fetch_assoc($result)){
    $output[] = $row;
}
json_encode($output);

答案 1 :(得分:0)

正如您所问,要删除它: 如果key是数字删除,则遍历它。

foreach($array as $key=>$var){ 
    if(is_numeric($key)){ 
        delete $array[$key]; 
    } 
}