# php多维数组排序以及实际工作中的应用

usort不保存键名

uasort 键名会保存下来

uksort 排序是对键名进行的

```<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Sorting Multidimensional Arrays</title>
<body>
<?php

\$a = [
[
'key1' => 940,
'key2' => 'blah',
],
[
'key1' => 23,
'key2' => 'this',
],
[
'key1' => 894,
'key2' => 'that',
],
];

var_dump(\$a);
// 比较的规则第一个小于第二个返回负数或false, 相当于第一个的值减去第二个, 如果前小后大则为负, 前大后小则为正, 两个一样, 则为0

//按第一个数组key1的数字从小到大排序
function asc_number_sort(\$x, \$y) {
echo "iteration x1 = ".\$x['key1'].' y = '.\$y['key1'];
if (\$x['key1'] > \$y['key1']) {
return true; // true或正数表示第二个参数应该排在前面, 小的在前
} elseif (\$x['key1'] < \$y['key1']) {
return false; // false或负数意味着第一个参数排第二个参数的前面, 小的在前
} else {
return 0; //表示两个数相等
}
}
usort(\$a, 'asc_number_sort');
echo '针对key1从小到大排序';
var_dump(\$a);

//对第二个关键字进行排序
function string_sort(\$x, \$y) {
return strcasecmp(\$x['key2'], \$y['key2']); // strcmp区分大小写 strcasecmp不区分大小写
}
usort(\$a, 'string_sort');
echo '针对key2按字母排序';
var_dump(\$a);

// create the array.
// Array structs
// StudentId = > ["name" => "Name", "grade" => xx.x];

\$students = [
256 => ['name' => 'Jon', 'grade' => '98.5'],
2 => ['name' => 'Vance', 'grade' => '85.1'],
9 => ['name' => 'Stephen', 'grade' => '94.0'],
364 => ['name' => 'Steve', 'grade' => '85.1'],
68 => ['name' => 'Rob', 'grade' => '74.6'],
];

function name_sort(\$x, \$y) {
return strcasecmp(\$x['name'], \$y['name']);
}

}

echo print_r(\$students, 1);
uasort(\$students, 'name_sort'); //保持键并使用自定义排序
echo print_r(\$students, 1);
echo print_r(\$students, 1);
?>
</body>
</html>```

```<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Sorting Multidimensional Arrays</title>
<body>
<?php
\$db = mysqli_connect('192.168.31.172', 'root', 'root', 'phpadvanced');
mysqli_query(\$db, "set names utf8");

\$parent_id = 0;
if(isset(\$_POST['parent_id']) && filter_var(\$_POST['parent_id'], FILTER_VALIDATE_INT, ['min_range' => 1])) {
\$parent_id = \$_POST['parent_id'];
}

echo \$q;
\$r = mysqli_query(\$db, \$q);

if(mysqli_affected_rows(\$db) == 1) {
echo '<p>任务添加成功</p>';
} else {
echo '<p>任务添加失败</p>';
}
}
?>
<fieldset>
<legend>添加一个任务</legend>
<p>任务: <input name="task" type="text" size="60" maxlength="100" required> </p>
<p>上级任务: <select name="parent_id">
<option value="0">无上级</option>

<?php
\$r = mysqli_query(\$db, \$q);
}
?>
</select></p>
<input name="submit" type="submit" value="添加这个任务" />
</fieldset>
</form>

<?php
// 对任务的父id进行排序
function parent_sort(\$x, \$y) {
return (\$x['parent_id'] > \$y['parent_id']);
}
echo '<h2>当前的任务列表</h2><ul>';
}
echo '</ul>';
?>
</body>
</html>```

```CREATE TABLE tasks (
task_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
parent_id INT UNSIGNED NOT NULL DEFAULT 0,
date_completed TIMESTAMP,
INDEX parent (parent_id),
INDEX completed (date_completed)
);```

php多维数组排序以及实际工作中的应用

• 0

开心

• 0

板砖

• 0

感动

• 0

有用

• 0

疑问

• 0

难过

• 0

无聊

• 0

震惊