<?php $data = [ [ 'id' => 1, 'name' => '张三', ], [ 'id' => 2, 'name' => '李四', ], [ 'id' => 3, 'name' => '王二', ], ];array_multisort对多维数组进行排序:
//升序 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 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));更多php数组排序