基于另一个数组的键对数组进行排序?

2022-01-31 00:00:00 arrays sorting php

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

相关文章