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

编程入门 行业动态 更新时间:2024-10-11 09:25:02
本文介绍了基于另一个数组的键对数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

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

本文发布于:2023-11-29 04:10:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645228.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!