Home  >  Article  >  Backend Development  >  PHP multidimensional array sorting and practical application

PHP multidimensional array sorting and practical application

WBOY
WBOYOriginal
2016-08-08 09:20:40982browse

Custom sorting function returns false or negative number which means the first parameter should be sorted before the second parameter, positive number or true otherwise, 0 is equal
usort does not save the key name
uasort key name will be saved
uksort sorting It is done on the key name

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Sorting Multidimensional Arrays</title>
</head>
<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']);
    }

    function grade_sort($x, $y) {
        return $x['grade'] < $y['grade'];
    }

echo print_r($students, 1);
uasort($students, 'name_sort'); //保持键并使用自定义排序
echo print_r($students, 1);
uasort($students, 'grade_sort');
echo print_r($students, 1);
?>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Sorting Multidimensional Arrays</title>
</head>
<body>
<?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>';
    }
}
?>
    <form action="add_task.php" method="post">
        <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
                    $q = 'SELECT task_id, parent_id, task FROM tasks WHERE date_completed="0000-00-00 00:00:00" ORDER BY date_added ASC';
                    $r = mysqli_query($db, $q);
                    $tasks = [];
                    while(list($task_id, $parent_id, $task) = mysqli_fetch_array($r, MYSQLI_NUM)) {
                        echo "<option value=\"$task_id\">$task</option>";
                        $tasks[] = ['task_id' => $task_id, 'parent_id' => $parent_id, 'task' => $task];
                    }
                    ?>
                </select></p>
            <input name="submit" type="submit" value="添加这个任务" />
        </fieldset>
    </form>

<?php
    // 对任务的父id进行排序
    function parent_sort($x, $y) {
        return ($x['parent_id'] > $y['parent_id']);
    }
    usort($tasks, 'parent_sort');
    echo '<h2>当前的任务列表</h2><ul>';
    foreach ($tasks as $task) {
        echo "<li>{$task['task']}</li>\n";
    }
echo '</ul>';
?>
</body>
</html>
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)
);

The above introduces PHP multi-dimensional array sorting and its application in practical work, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Yii2 set time zoneNext article:Yii2 set time zone