根据另一个数组按键对数组进行排序? [英] Sort an Array by keys based on another Array?

查看:39
本文介绍了根据另一个数组按键对数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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_mergearray_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.

这篇关于根据另一个数组按键对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆