在 PHP 中根据一些重复值对数组进行排序
我有一个包含以下格式字符串的数组:
[0] => "title|url|score|user|date"
[1] => "title|url|score|user|date"
[2] => "title|url|score|user|date"
[3] => "title|url|score|user|date"
...
score
字段是一个并不总是唯一的 int (例如,多个条目的分数可以为 0)。我希望根据字符串的 score
值对该数组中的字符串进行排序。最初,我尝试迭代数组并使用与投票分数相对应的键创建一个新数组。我很快意识到数组中不能有重复的键。
有没有一个好的干净的方法来做到这一点?
I have an array containing strings of this format:
[0] => "title|url|score|user|date"
[1] => "title|url|score|user|date"
[2] => "title|url|score|user|date"
[3] => "title|url|score|user|date"
...
The score
field is an int that is not always unique (for example, more than one entry can have a score of 0). I'm looking to sort the strings in this array based on their score
value. Originally, I tried iterating through the array and making a new one with keys corresponding to the vote score. I soon realized that you can't have duplicate keys in an array.
Is there a good clean way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
查看 PHP 的 usort 函数
替换
['score']
然而,您从字符串中提取分数Look into PHP's usort function
Replace
['score']
with however you are extracting the scores from the strings首先,您需要使用
explode
将字符串转换为数组,以便可以进行比较:这将使
$converted
看起来像:然后您可以使用以下代码对数组进行排序我的回答此处轻松指定您想要的任何排序标准想:
First you need to turn the strings into arrays with
explode
so you can do the comparisons:This will make
$converted
look like:Then you can sort the array using the code from my answer here by easily specifying any sort criteria you want:
就我个人而言,我很想迭代数组,用 | 分割它并将其放入一个新的多维数组中,例如这样:
然后它就变得很容易排序,只需使用这样的函数:
即这样做:
Personally I'd be tempted to iterate through the array, split it by the |'s and put it into a new multi-dimensional array, for example something like this:
Then it becomes easy to sort, just use a function like this:
i.e. do this:
使用 asort 函数会非常容易:
这 4 行代码,当给定 $data: 时,
将生成 $sorted:
并且只需再多 2 行,您就可以将数组的每个元素中的项目恢复为原始顺序/格式:
将 $data 设置为:
It would be very easy using the asort function:
these 4 lines of code, when given $data:
will generate $sorted:
and with just 2 more lines you can have the items in each element of the array back in the original order/format:
setting $data to:
创建一个新的数组数组:
[0] => array("score", old_array[0])
然后排序。
Create a new array of arrays:
[0] => array("score", old_array[0])
Then sort.