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.
这篇关于基于另一个数组的键对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:基于另一个数组的键对数组进行排序?
基础教程推荐
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何替换eregi() 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
