Home > Backend Development > PHP Tutorial > How Can I Custom Sort PHP Array Keys Using an External Array?

How Can I Custom Sort PHP Array Keys Using an External Array?

DDD
Release: 2024-12-19 21:18:10
Original
388 people have browsed it

How Can I Custom Sort PHP Array Keys Using an External Array?

Custom Key Sorting in PHP Based on External Array

In PHP, it's possible to sort the keys of an associative array based on the order specified in another array. This can be achieved by utilizing the array_merge function:

$customer = [
    'address' => '123 fake st',
    'name' => 'Tim',
    'dob' => '12/08/1986',
    'dontSortMe' => 'this value doesn\'t need to be sorted'
];

$sortOrder = ['name', 'dob', 'address'];
$properOrderedArray = array_merge(array_flip($sortOrder), $customer);
Copy after login

The array_merge function combines two arrays, starting with the array specified as the first argument (in this case, the custom order) and overwriting or adding keys from the second array (the customer data) into the merged array.

Output:

[
    'name' => 'Tim',
    'dob' => '12/08/1986',
    'address' => '123 fake st',
    'dontSortMe' => 'this value doesn\'t need to be sorted'
]
Copy after login

It's important to note that this method preserves the original data in the $customer array while creating a new $properOrderedArray with the specified order.

The above is the detailed content of How Can I Custom Sort PHP Array Keys Using an External Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template