Sort an Array by keys based on another Array?(基于另一个数组的键对数组进行排序?)
问题描述
在 PHP 中可以做这样的事情吗?您将如何编写函数?这是一个例子.顺序是最重要的.
Is it possible in PHP to do something like this? How would you go about writing a function? Here is an example. The order is the most important thing.
$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';
我想做类似的事情
$properOrderedArray = sortArrayByArray($customer, array('name', 'dob', 'address'));
因为最后我使用了一个 foreach() 并且它们的顺序不正确(因为我将值附加到一个需要以正确顺序排列的字符串并且我事先不知道所有数组键/值).
Because at the end I use a foreach() and they're not in the right order (because I append the values to a string which needs to be in the correct order and I don't know in advance all of the array keys/values).
我查看了 PHP 的内部数组函数,但您似乎只能按字母或数字排序.
I've looked through PHP's internal array functions but it seems you can only sort alphabetically or numerically.
推荐答案
只要使用 array_merge
或 array_replace
.array_merge
从你给它的数组开始(以正确的顺序)并用你的实际数组中的数据覆盖/添加键:
Just use array_merge
or array_replace
. array_merge
works by starting with the array you give it (in the proper order) and overwriting/adding the keys with data from your actual array:
$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';
$properOrderedArray = array_merge(array_flip(array('name', 'dob', 'address')), $customer);
// or
$properOrderedArray = array_replace(array_flip(array('name', 'dob', 'address')), $customer);
// $properOrderedArray: array(
// 'name' => 'Tim',
// 'dob' => '12/08/1986',
// 'address' => '123 fake st',
// 'dontSortMe' => 'this value doesnt need to be sorted')
PS:我正在回答这个陈旧"的问题,因为我认为作为先前答案给出的所有循环都是多余的.
PS: I'm answering this 'stale' question, because I think all the loops given as previous answers are overkill.
这篇关于基于另一个数组的键对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:基于另一个数组的键对数组进行排序?
基础教程推荐
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在多维数组中查找最大值 2021-01-01