永发信息网

php删除数组中相同的元素

答案:7  悬赏:20  手机版
解决时间 2021-11-30 04:04
  • 提问者网友:皆是孤独
  • 2021-11-29 11:10
php删除数组中相同的元素
最佳答案
  • 五星知识达人网友:何以畏孤独
  • 2021-11-29 11:52
array_unique
(PHP 4 >= 4.0.1, PHP 5, PHP 7)
array_unique — 移除数组中重复的值

说明

array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

array_unique() 接受 array 作为输入并返回没有重复值的新数组。

注意键名保留不变。array_unique() 先将值作为字符串排序,然后对每个值只保留第一个遇到的键名,接着忽略所有后面的键名。这并不意味着在未排序的 array 中同一个值的第一个出现的键名会被保留。

Note: 当且仅当 (string) $elem1 === (string) $elem2 时两个单元被认为相同。就是说,当字符串的表达一样时。 第一个单元将被保留。

参数

array

输入的数组。
sort_flags

The optional second parameter sort_flags may be used to modify the sorting behavior using these values:

Sorting type flags:

SORT_REGULAR - compare items normally (don't change types)

SORT_NUMERIC - compare items numerically

SORT_STRING - compare items as strings

SORT_LOCALE_STRING - compare items as strings, based on the current locale.

返回值

Returns the filtered array.

更新日志

版本
说明

5.2.10 Changed the default value of sort_flags back to SORT_STRING.
5.2.9 Added the optional sort_flags defaulting to SORT_REGULAR. Prior to 5.2.9, this function used to sort the array with SORT_STRING internally.

范例

Example #1 array_unique() 例子

$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>

以上例程会输出:

Array
(
[a] => green
[0] => red
[1] => blue
)

Example #2 array_unique() 和类型

$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
?>

以上例程会输出:

array(2) {
[0] => int(4)
[2] => string(1) "3"
}

参见

array_count_values() - 统计数组中所有的值出现的次数

注释

Note: Note that array_unique() is not intended to work on multi dimensional arrays.
全部回答
  • 1楼网友:轻雾山林
  • 2021-11-29 18:08
删除的时候标明i的值,即数组的下表既可删除。Array[i]
  • 2楼网友:深街酒徒
  • 2021-11-29 17:18
$arr = array_flip(array_flip($arr));
  • 3楼网友:野慌
  • 2021-11-29 15:48
$array=array(0=>"撒旦",1=>"法",2=>"撒旦",3=>"搜索");
print_r($array);
echo "
";
$array = array_unique($array);
$qwe=$array;
print_r($array);
echo "
";
print_r($qwe);
?>
  • 4楼网友:轻熟杀无赦
  • 2021-11-29 14:46
有一个函数就可以直接删除
$array = array_unique($array);
$array就是你的数组。
  • 5楼网友:罪歌
  • 2021-11-29 14:11
这是我写得代码,你可以参照下


$aa=array("apple","banana","pear","apple","wail","watermalon");

$bb=array_unique($aa);

print_r($bb);

?>

结果如下:Array ( [0] => apple [1] =>
banana [2] => pear [4] => wail [5]
=> watermalon )

希望能对你有所帮助
  • 6楼网友:洒脱疯子
  • 2021-11-29 13:08
array_unique($str);
用这个函数,直接删除相同值
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯