在 PHP 数组中保留插入顺序


Preserve the insert order in a PHP array

我有一个 Ajax 调用使用的 PHP 页面,我想以 JSON 的形式返回有序的项目列表。但是,无论我在查询的"order by"子句中使用哪个字段,数组始终按其键 ID 字段排序。

有没有办法保留 PHP 数组中每个项目的插入顺序?

这是生成 JSON 数组的代码:

$Soggetti = array();
while($row = $db->fetch_array($query))
{
    $Soggetti[$row['ID']] = array();
    $Soggetti[$row['ID']]['Denominazione'] = $row['Denominazione'];
    $Soggetti[$row['ID']]['Indirizzo'] =   $row['Indirizzo'].','.$row['Comune'].', '.$row['Provincia'];
    $Soggetti[$row['ID']]['Superficie'] = $row['Superficie'];
    $Soggetti[$row['ID']]['Lat'] = $row['Lat'];
    $Soggetti[$row['ID']]['Lng'] = $row['Lng'];
    $Soggetti[$row['ID']]['Tipologia'] = $row['Tipologia'];
    $Soggetti[$row['ID']]['CodiceIscrizione'] = $row['CodiceIscrizione'];
    $Soggetti[$row['ID']]['Visitato'] = intval($row['Visitato']);
}
echo json_encode($Soggetti)

如果问题出在解释 JSON 的位置,则在客户端中,您可以使用此语法返回 JSON 数组(括在 [] 中(而不是 JSON 对象(括在 {} 中(。

echo json_encode(array_values($Soggetti));

您正在构建一个二维数组,其中第一维上的键是 id。 假设id是数字,您最终将得到 JSON 中的嵌套对象,顶级键是数字 id 值。这里的问题是对象属性不能保证顺序。

若要获取查询结果的顺序,只需在结果集循环中生成一个一维数组,如下所示:

$tempArray = array();
$tempArray['ID'] = $row['ID'];
$tempArray['Denominazione'] = $row['Denominazione'];
$tempArray['Indirizzo'] = $row['Indirizzo'].','.$row['Comune'].', '.$row['Provincia'];
$tempArray['Superficie'] = $row['Superficie'];
$tempArray['Lat'] = $row['Lat'];
$tempArray['Lng'] = $row['Lng'];
$tempArray['Tipologia'] = $row['Tipologia'];
$tempArray['CodiceIscrizione'] = $row['CodiceIscrizione'];
$tempArray['Visitato'] = intval($row['Visitato']);
$Soggetti[] = $tempArray;

将编码为 JSON 作为对象数组,其中数组根据结果集中的顺序从 0 开始数字索引。

你需要

MySQL语句的ORDER BY子句。

在这种情况下,您希望按ID排序,

并按升序排序,因此;

SELECT * from your_table ORDER BY id ASC

参考:MySQL 排序

问题可能出在您的 mysql 查询中,请尝试:

select * from table_name order by ID asc