php对多维数组进行排序

时间:2022-12-04 19:00:40

对多维数组排序:

<?php

$data = [
[
'id' => 13,
'name' => 'Arthur Dent',
],
[
'id' => 22,
'name' => 'Ford Prefect',
],
[
'id' => 5,
'name' => 'Trillian Astra',
],
];

//对多维数组进行排序,就是这么简单!
// array_multisort(array_column($data, 'id'), SORT_ASC, $data);

array_multisort(array_column($data, 'id'), SORT_DESC, $data);
echo "<pre>";
print_r($data);
echo "</pre>";

php对多维数组进行排序

没错,就上面一句话就解决问题了!

从数据库取出数据:

<?php

try {
// 连接数据库
$pdo = new PDO("mysql:host=localhost;dbname=fp_company_v2", "root", "123456");

//设置取值模式,取索引数组
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

} catch (PDOException $e) {
echo '数据库连接失败' . $e->getMessage();
}

$sql = "select company.company_name as '公司名称',count(workers.company_id) as '用户数' from company,workers where company.id=workers.company_id group by company_name ";

// 取出所有结果集
$res = $pdo->query($sql)->fetchAll();

//对数组进行排序
$res = array_sort($res, '用户数', SORT_DESC);

//把排序后的数组写入到文件
file_put_contents('d:/tongji.json', print_r($res, true));