PHP 使用特定字母对数组进行排序
我有一个如下所示的 php 数组:
Array (
[0] => Array ( [value] => 5 [label] => Akon )
[1] => Array ( [value] => 6 [label] => Angel )
[2] => Array ( [value] => 7 [label] => Britny )
[3] => Array ( [value] => 9 [label] => Mark Anthony )
[4] => Array ( [value] => 8 [label] => Michel )
[5] => Array ( [value] => 4 [label] => Shaggy )
[6] => Array ( [value] => 3 [label] => Smith )
)
我需要这个数组按特定字母排序。例如,如果我按“M”字母数组排序,则应如下所示。
Array (
[3] => Array ( [value] => 9 [label] => Mark Anthony )
[4] => Array ( [value] => 8 [label] => Michel )
[6] => Array ( [value] => 3 [label] => Smith )
[0] => Array ( [value] => 5 [label] => Akon )
[1] => Array ( [value] => 6 [label] => Angel )
[2] => Array ( [value] => 7 [label] => Britny )
[5] => Array ( [value] => 4 [label] => Shaggy )
)
乞求信应该出现在数组的第一个。(这里以m开头) 我非常感谢您提供的任何帮助。非常感谢...
I have an php array like below:
Array (
[0] => Array ( [value] => 5 [label] => Akon )
[1] => Array ( [value] => 6 [label] => Angel )
[2] => Array ( [value] => 7 [label] => Britny )
[3] => Array ( [value] => 9 [label] => Mark Anthony )
[4] => Array ( [value] => 8 [label] => Michel )
[5] => Array ( [value] => 4 [label] => Shaggy )
[6] => Array ( [value] => 3 [label] => Smith )
)
I need this array sort by specific letter. For example, if I sort by this "M" letter array should look like below.
Array (
[3] => Array ( [value] => 9 [label] => Mark Anthony )
[4] => Array ( [value] => 8 [label] => Michel )
[6] => Array ( [value] => 3 [label] => Smith )
[0] => Array ( [value] => 5 [label] => Akon )
[1] => Array ( [value] => 6 [label] => Angel )
[2] => Array ( [value] => 7 [label] => Britny )
[5] => Array ( [value] => 4 [label] => Shaggy )
)
The begging letter should comes to first of array.(here begin with m)
I greatly appreciated your any kind of help. Thank you very much...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你的比较逻辑将是这样的:
在代码中
Your comparison logic is going to be like this:
in code
只是比较两个字符串中字母的位置。如果该字母不在字符串之一内(
strpos()
返回false
),则假定为“无限”索引 (PHP_INT_MAX
),Just compares the position of the letter within the two strings. If the letter is not within one of the strings (
strpos()
returnsfalse
), it assumes an "infinite" index (PHP_INT_MAX
),这是我在 php.net 上找到的一个示例,可以帮助您维护索引: http://www.php.net/manual/en/function.sort.php#99419
this is an example i found on php.net that could help you and maintain the index : http://www.php.net/manual/en/function.sort.php#99419
基于反映字母的比较,按值对数据进行排序(演示):
Sort the data by the value based on the comparison reflecting the letter (Demo):
使用
usort
按函数排序。该函数可以包含您想要放入的任何逻辑,只要返回值指示排序顺序即可(有关详细信息,请参阅链接)。Use
usort
to sort by a function. The function can contain any logic you want to put in, as long as the return value indicates sort order (see link for details).