如何在php中对数组进行排序 [英] How to sort an array in php

查看:105
本文介绍了如何在php中对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望相同的值具有相同的索引 例如

i want the same value has the same index for example

1 2 2 3 5

排序后:

array(
0=>1
1=>2
1=>2
3=>3
4=>5);

但是我们不能在php数组中设置重复索引.

but we can not set duplicate index in the array of php.

推荐答案

有一个 函数! (我回答的是主题,而不是正文,没有在那里关注您,但这是您在php中排序的方式)

There's a sort function in php! ( I answer the topic and not the body, didn't quite follow you there, but here's how you sort in php )

示例

<?php

$fruits = array("lemon", "orange", "banana", "apple");

sort($fruits);

foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

重复

在上面的示例中,重复项仅具有自己的索引,因此该数组:

In the above example duplicates will just have their own indexes so the array:

5 4 5 1 3 1 2

看起来会像这样

1 1 2 3 4 5 5

这可能不是您要查找的,您想要的是另一种数据集,而不仅仅是简单的数组,也许您想要的是哈希表或每行上只有一个链表.

This might not be what you are looking for, what you want is another type of dataset than just a simple array, maybe you want a hashtable or just a linked list on each row.

如果可以的话,可以使用 array_unique 删除重复项 $newArray=array_unique($arr);

If you are okay with it, you can remove the duplicates by using array_unique $newArray=array_unique($arr);

这将导致数组看起来像这样

Which would lead to having an array looking like this

1 2 3 4 5

这篇关于如何在php中对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆