Home Backend Development PHP Tutorial PHP How to sort an array by value while retaining the original key names?

PHP How to sort an array by value while retaining the original key names?

May 04, 2024 am 08:06 AM
Array sort Keywords: php

PHP provides two ways to sort associative arrays by value: Use the asort() function: sort the values ​​from small to large while retaining the original key names. Using the usort() function and closures: Sort values ​​by a custom comparison function while preserving the original key names.

PHP 如何按值对数组进行排序,同时保留原始键名?

Using the asort() function

PHP’s asort() function Associative arrays can be sorted by value while preserving the original key names. It accepts an associative array as argument and sorts the values ​​from smallest to largest.

<?php
$arr = [
    "apple" => 5,
    "banana" => 3,
    "orange" => 2,
    "grape" => 4,
];

asort($arr);

print_r($arr);
?>
Copy after login

Output:

Array
(
    [orange] => 2
    [banana] => 3
    [grape] => 4
    [apple] => 5
)
Copy after login
Copy after login

As you can see, the values ​​of the array have been sorted from small to large, but the key names remain unchanged.

Using usort() Functions and closures

Another way is to use usort() Functions and closures Bag. usort() Accepts a callback function as a parameter, which is used to compare elements in the array. A closure is an anonymous function that can be used as a callback.

<?php
$arr = [
    "apple" => 5,
    "banana" => 3,
    "orange" => 2,
    "grape" => 4,
];

usort($arr, function ($a, $b) {
    return $a[1] - $b[1];
});

print_r($arr);
?>
Copy after login

Output:

Array
(
    [orange] => 2
    [banana] => 3
    [grape] => 4
    [apple] => 5
)
Copy after login
Copy after login

In this case, the closure compares the value of each element ($a[1] and $b[ 1]), and returns -1, 0, or 1, depending on which value is greater.

The above is the detailed content of PHP How to sort an array by value while retaining the original key names?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Fast array sorting method that preserves key names in PHP Fast array sorting method that preserves key names in PHP May 02, 2024 pm 03:06 PM

Fast array sorting method in PHP that preserves key names: Use the ksort() function to sort the keys. Use the uasort() function to sort using a user-defined comparison function. Practical case: To sort an array of user IDs and scores by score while retaining the user ID, you can use the uasort() function and a custom comparison function.

JS array sorting: in-depth analysis of the working principle and mechanism of the sort() method JS array sorting: in-depth analysis of the working principle and mechanism of the sort() method Dec 28, 2023 am 11:47 AM

To deeply understand JS array sorting: the principles and mechanisms of the sort() method, specific code examples are required. Introduction: Array sorting is one of the very common operations in our daily front-end development work. The array sorting method sort() in JavaScript is one of the most commonly used array sorting methods. However, do you really understand the principles and mechanisms of the sort() method? This article will give you an in-depth understanding of the principles and mechanisms of JS array sorting, and provide specific code examples. 1. Basic usage of sort() method

How to use PHP to develop simple navigation bar and URL collection functions How to use PHP to develop simple navigation bar and URL collection functions Sep 20, 2023 pm 03:14 PM

How to use PHP to develop a simple navigation bar and website collection function. The navigation bar and website collection function are one of the common and practical functions in web development. This article will introduce how to use PHP language to develop a simple navigation bar and URL collection function, and provide specific code examples. Create a navigation bar interface First, we need to create a navigation bar interface. The navigation bar usually contains links for quick navigation to other pages. We can use HTML and CSS to design and arrange these links. The following is a simple navigation bar interface

How to keep key names after sorting PHP array by value? How to keep key names after sorting PHP array by value? May 02, 2024 pm 04:09 PM

The way to sort an array by value in PHP while preserving the key names is to use the usort() function to sort the array by value. Pass an anonymous function to the usort() function as a comparison function, which returns the difference in element values. usort() will sort the array according to the anonymous function while keeping the key names unchanged.

Guide to writing a custom sorting algorithm for PHP arrays Guide to writing a custom sorting algorithm for PHP arrays Apr 27, 2024 pm 06:12 PM

How to write a custom PHP array sorting algorithm? Bubble sort: Sorts an array by comparing and exchanging adjacent elements. Selection sort: Select the smallest or largest element each time and swap it with the current position. Insertion sort: Insert elements one by one into the sorted part.

Using Golang reflection to implement structure field traversal and modification Using Golang reflection to implement structure field traversal and modification Apr 03, 2024 pm 12:06 PM

Go reflection can be used to traverse and modify structure fields. Field traversal: Use reflect.TypeOf and reflect.Field to traverse the structure fields. Field modification: Access and modify the values ​​of structure fields through Elem and Set. Practical case: Use reflection to convert the structure into a map, and then convert the map into JSON.

Sort arrays according to custom sorting rules in PHP, retaining original key names Sort arrays according to custom sorting rules in PHP, retaining original key names May 04, 2024 am 09:27 AM

In PHP, use the uasort() function to sort an array according to custom sorting rules while retaining the original key names. A custom comparison function is a function that takes two elements as input and returns an integer: a negative number means the former is less than the latter, zero means they are equal, and a positive number means the former is greater than the latter.

PHP and GMP tutorial: How to implement multiplication of large numbers PHP and GMP tutorial: How to implement multiplication of large numbers Jul 29, 2023 pm 03:29 PM

PHP and GMP Tutorial: How to Implement Multiplication of Large Numbers Introduction: When we need to deal with large integers in programming, ordinary integer types cannot meet the needs. In PHP, the GMP (GNUMultiplePrecision) extension provides the ability to handle arbitrary precision integers. This tutorial will focus on how to use PHP's GMP extension to implement multiplication of large numbers. Install and enable the GMP extension Before we begin, we need to make sure that PHP has the GMP extension installed and enabled. OK

See all articles