Maison >développement back-end >tutoriel php >php多维数组排序以及实际工作中的应用
自定义排序函数返回false或负数意味着第一个参数应该排在第二个参数的前面, 正数或true反之, 0相等
usort不保存键名
uasort 键名会保存下来
uksort 排序是对键名进行的
<meta charset="utf-8"> <title>Sorting Multidimensional Arrays</title> <?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'] ["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']); } function grade_sort($x, $y) { return $x['grade']
<meta charset="utf-8"> <title>Sorting Multidimensional Arrays</title> <?php $db = mysqli_connect('192.168.31.172', 'root', 'root', 'phpadvanced'); mysqli_query($db, "set names utf8"); if(!empty($_POST['task'])) { $parent_id = 0; if(isset($_POST['parent_id']) && filter_var($_POST['parent_id'], FILTER_VALIDATE_INT, ['min_range' => 1])) { $parent_id = $_POST['parent_id']; } $task = mysqli_real_escape_string($db, strip_tags($_POST['task'])); $q = "INSERT INTO tasks (parent_id, task) VALUES ($parent_id, '$task')"; echo $q; $r = mysqli_query($db, $q); if(mysqli_affected_rows($db) == 1) { echo '<p>任务添加成功</p>'; } else { echo '<p>任务添加失败</p>'; } } ?>$y['parent_id']); } usort($tasks, 'parent_sort'); echo '
CREATE TABLE tasks ( task_id INT UNSIGNED NOT NULL AUTO_INCREMENT, parent_id INT UNSIGNED NOT NULL DEFAULT 0, task VARCHAR(100) NOT NULL, date_added TIMESTAMP NOT NULL, date_completed TIMESTAMP, PRIMARY KEY (task_id), INDEX parent (parent_id), INDEX added (date_added), INDEX completed (date_completed) );
以上就介绍了php多维数组排序以及实际工作中的应用,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。