二维阵列模拟/比较


2 dimensional array simulation/comparison

我有以下几行。。。

$getmodels = array(
array('value' => 1, 'text' => 'Services'),
array('value' => 2, 'text' => 'Customers'),
array('value' => 3, 'text' => 'Operators'),
array('value' => 4, 'text' => 'Supports'),
array('value' => 5, 'text' => 'Guests'),
);
echo json_encode($getmodels);

现在,我尝试通过表及其行内容来复制结果。。

$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$model = $db_connection->query("SELECT id, name FROM vhclmodel ORDER BY name;");
$getmodels = array();
while ($row = mysql_fetch_assoc($model)) {
   $getmodels[] = array('value' => $row['id'], 'text' => $row['name']);
}
echo json_encode($getmodels);

我不能得到同样的结果,请帮忙。。还是个新手。TIA。。。

您将msqli与不推荐使用的mysql函数混合使用。使用$model->fetch_assoc()而不是mysql_fetch_assoc($model)

所以试试这个:

$getmodels = array();
while ($row = $model->fetch_assoc()) {
    $getmodels[] = array('value' => $row['id'], 'text' => $row['name']);
}
echo json_encode($getmodels);

请参阅http://us2.php.net/manual/en/mysqli-result.fetch-assoc.php

正如Mark在评论中指出的,手动数组是按id排序的,而DB查询是按名称排序的。如果这很重要,只需更改您的查询:

SELECT id, name FROM vhclmodel ORDER BY id