TL; DR
按键排序/分组数组而不向数组添加另一个级别(由jQuery插件解析的数据)?
细节
我正在构建一个数组以返回一些< select> DOM元素.
它将CC(引擎大小的东西)作为参数并将其用作键,问题在于对数组进行排序.
假设用户选择此范围的CC:
50, 100, 125
50 has 32 options available
100 has 3 options available
125 has 12 options available
我当前的代码遍历CC,执行SQL以获取选项,并使用循环计数器创建如下的键:
$options[$cc. $id] = $someValue;
这可以按照您的预期工作,但是我的输出显示的结果并不完全符合我需要的顺序(CC ASC – 因此所有50个应该首先显示在一起).
问题是
50 with 32 goes upto 5031 as a key.
100 with 3 goes upto 1002 as a key.
125 with 12 goes upto 12511 as a key.
现在希望你能清楚地看到这个问题. 5031大于1002.因此,通过9循环计数器的50cc选项大于100cc选项.
(为了清楚起见,示例输出是):
50cc Option 1
50cc Option 2
50cc Option 3
50cc Option 4
50cc Option 5
100cc Option 1
100cc Option 2
100cc Option 3
50cc Option 6
50cc Option 7
也许最初的问题是我是如何创建密钥的,但我尝试使用带有几个不同标志的ksort来尝试实现我的目标,但没有一个标志似乎针对我所追求的目标:
06001
如何在不向我的阵列添加另一个级别的情况下对键进行排序/分组(数据是由需要特定格式的数据的jQuery插件解析的)?
编辑:完整的脚本
if (strpos(PHP_OS, 'Linux') > -1) {
require_once $_SERVER['DOCUMENT_ROOT']. '/app/connect.php';
} else {
require_once getcwd(). '\\..\\..\\..\\..\\app\\connect.php';
}
$make = $_POST['make'];
$cc = $_POST['cc'];
$sql = 'SELECT * FROM `table`
WHERE `UKM_CCM` = :cc
AND `UKM_Make` = :make
ORDER BY `UKM_Model`, `UKM_StreetName`, `Year` ASC;';
$options = array();
foreach ($cc as $k => $value)
{
$res = $handler->prepare($sql);
$res->execute(array(':cc' => $value, ':make' => $make));
$data = $res->fetchAll(PDO::FETCH_ASSOC);
$i = 0;
if (count($data) > 0) {
foreach ($data as $result)
{
$arrayKey = sprintf('%03d%02d', $cc, $i);
$epid = $result['ePID'];
$make = $result['UKM_Make'];
$model = $result['UKM_Model'];
$cc = $result['UKM_CCM'];
$year = $result['Year'];
$sub = $result['UKM_Submodel'];
$street = $result['UKM_StreetName'];
$options[$arrayKey]['name'] = $make. ' ' .$model. ' ' .$cc. ' ' .$year. ' ' .$sub. ' ' .$street;
$options[$arrayKey]['value'] = $epid;
$options[$arrayKey]['checked'] = false;
$options[$arrayKey]['attributes']['data-epid'] = $epid;
$options[$arrayKey]['attributes']['data-make'] = $make;
$options[$arrayKey]['attributes']['data-model'] = $model;
$options[$arrayKey]['attributes']['data-cc'] = $cc;
$options[$arrayKey]['attributes']['data-year'] = $year;
$options[$arrayKey]['attributes']['data-sub'] = $sub;
$options[$arrayKey]['attributes']['data-street'] = $street;
$i++;
}
}
}
ksort($options, SORT_STRING);
echo json_encode($options);
解决方法:
您可以将密钥格式化为cc的3位数和选项的2位数…
$options[sprintf('%03d%02d', $cc, $id)] = $someValue;
它应该给你键05031和10002.
然后使用SORT_STRING强制它将它们排序为字符串(尽管它们也会按数字排序)
标签:php,arrays,mysql,sorting,ksort
来源: https://codeday.me/bug/20190701/1346167.html