php 根据另一个数组按键对数组进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/348410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort an Array by keys based on another Array?
提问by alex
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.
在 PHP 中可以做这样的事情吗?你会如何编写一个函数?这是一个例子。顺序是最重要的。
$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';
And I'd like to do something like
我想做类似的事情
$properOrderedArray = sortArrayByArray($customer, array('name', 'dob', 'address'));
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).
因为最后我使用了 foreach() 并且它们的顺序不正确(因为我将值附加到需要按正确顺序排列的字符串中,并且我事先不知道所有数组键/值)。
I've looked through PHP's internal array functions but it seems you can only sort alphabetically or numerically.
我查看了 PHP 的内部数组函数,但似乎只能按字母顺序或数字顺序排序。
回答by Darkwaltz4
Just use array_mergeor array_replace. Array_mergeworks by starting with the array you give it (in the proper order) and overwriting/adding the keys with data from your actual array:
只需使用array_merge或array_replace。Array_merge从你给它的数组开始(按正确的顺序),然后用你的实际数组中的数据覆盖/添加键:
$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', 'address' => '123 fake st', 'dob' => '12/08/1986', 'dontSortMe' => 'this value doesnt need to be sorted')
ps - I'm answering this 'stale' question, because I think all the loops given as previous answers are overkill.
ps - 我正在回答这个“陈旧”的问题,因为我认为作为以前的答案给出的所有循环都是矫枉过正的。
回答by Eran Galperin
There you go:
你去吧:
function sortArrayByArray(array $array, array $orderArray) {
$ordered = array();
foreach ($orderArray as $key) {
if (array_key_exists($key, $array)) {
$ordered[$key] = $array[$key];
unset($array[$key]);
}
}
return $ordered + $array;
}
回答by Peter de Groot
How about this solution
这个解决方案怎么样
$order = array(1,5,2,4,3,6);
$array = array(
1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four',
5 => 'five',
6 => 'six'
);
uksort($array, function($key1, $key2) use ($order) {
return (array_search($key1, $order) > array_search($key2, $order));
});
回答by ekuser
Another way for PHP >= 5.3.0:
PHP >= 5.3.0 的另一种方法:
$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';
$customerSorted = array_replace(array_flip(array('name', 'dob', 'address')), $customer);
Result:
结果:
Array (
[name] => Tim
[dob] => 12/08/1986
[address] => 123 fake st
[dontSortMe] => this value doesnt need to be sorted
)
Works fine with string and numeric keys.
适用于字符串和数字键。
回答by OIS
function sortArrayByArray(array $toSort, array $sortByValuesAsKeys)
{
$commonKeysInOrder = array_intersect_key(array_flip($sortByValuesAsKeys), $toSort);
$commonKeysWithValue = array_intersect_key($toSort, $commonKeysInOrder);
$sorted = array_merge($commonKeysInOrder, $commonKeysWithValue);
return $sorted;
}
回答by hakre
Take one array as your order:
以一个数组作为您的订单:
$order = array('north', 'east', 'south', 'west');
You can sort another array based on values using array_intersectDocs:
您可以使用array_intersectDocs根据值对另一个数组进行排序:
/* sort by value: */
$array = array('south', 'west', 'north');
$sorted = array_intersect($order, $array);
print_r($sorted);
Or in your case, to sort by keys, use array_intersect_keyDocs:
或者在您的情况下,要按键排序,请使用array_intersect_keyDocs:
/* sort by key: */
$array = array_flip($array);
$sorted = array_intersect_key(array_flip($order), $array);
print_r($sorted);
Both functions will keep the order of the first parameter and will only return the values (or keys) from the second array.
这两个函数都将保持第一个参数的顺序,并且只返回第二个数组中的值(或键)。
So for these two standard cases you don't need to write a function on your own to perform the sorting/re-arranging.
因此,对于这两种标准情况,您无需自己编写函数来执行排序/重新排列。
回答by Baptiste Bernard
I used the Darkwaltz4's solution but used array_fill_keysinstead of array_flip, to fill with NULLif a key is not set in $array.
我用Darkwaltz4的解决方案,但使用array_fill_keys的替代array_flip,以填补NULL如果钥匙没有设置$array。
$properOrderedArray = array_replace(array_fill_keys($keys, null), $array);
回答by Jenovai Matyas
Without magic...
没有魔法...
$array=array(28=>c,4=>b,5=>a);
$seq=array(5,4,28);
SortByKeyList($array,$seq) result: array(5=>a,4=>b,28=>c);
function sortByKeyList($array,$seq){
$ret=array();
if(empty($array) || empty($seq)) return false;
foreach($seq as $key){$ret[$key]=$dataset[$key];}
return $ret;
}
回答by Boombastic
IF you have array in your array, you'll have to adapt the function by Eran a little bit...
如果数组中有数组,则必须稍微调整 Eran 的函数...
function sortArrayByArray($array,$orderArray) {
$ordered = array();
foreach($orderArray as $key => $value) {
if(array_key_exists($key,$array)) {
$ordered[$key] = $array[$key];
unset($array[$key]);
}
}
return $ordered + $array;
}
回答by Doglas
This function return a sub and sorted array based in second parameter $keys
此函数返回基于第二个参数 $keys 的子数组和排序数组
function array_sub_sort(array $values, array $keys){
$keys = array_flip($keys);
return array_merge(array_intersect_key($keys, $values), array_intersect_key($values, $keys));
}
Example:
例子:
$array_complete = [
'a' => 1,
'c' => 3,
'd' => 4,
'e' => 5,
'b' => 2
];
$array_sub_sorted = array_sub_sort($array_complete, ['a', 'b', 'c']);//return ['a' => 1, 'b' => 2, 'c' => 3];

