如何在 php 中获取唯一数组
How to get unique array in php
我有一个这样的数组:
Array([0] => 1,[1] => 2,[2] => 3,[3] => 3,[4] => 4,[5] => 5,[6] => 5,[7] => 6,[8] => 6,[9] => 6,[10] => 7,[11] => 8,[12] => 8,[13] => 8,[14] => 8,[15] => 9,[16] => 9,[17] => 9,[18] => 9,[19] => 9)
但我想要的结果是这样的:
Array([0] => 1,[1] => 2,[3] => 3,[4] => 4,[6] => 5,[9] => 6,[10] => 7,[14] => 8,[19] => 9)
这不仅消除了相同数组的值,而且消除了看起来是相同值的最后一个索引/键的值的相同值。谁能帮帮我?
array_unique()
Takes an input array and returns a new array without duplicate values.
示例:
array_unique($your_array);
可以使用数组操作函数
array_unique($arr);
array_unique()
函数通过你可以得到数组的唯一值。
<?php
$data=Array(1,2,3,3,4,5,5,6,6,6,7,8,8,8,8,9,9,9,9);
echo '<pre>';
print_r($data);
$ans=array_unique($data);
print_r($ans);
echo '</pre>';
?>
<?php $arr=Array("[0]" => 1,"[1]" => 2,"[2]" => 3,"[3]" => 3,"[4]" => 4,"[5]" => 5,"[6]" => 5,"[7]" => 6,"[8]" => 6,"[9]" => 6,"[10]" => 7,"[11]" => 8,"[12]" => 8,"[13]" => 8,"[14]" => 8,"[15]" => 9,"[16]" => 9,"[17]" => 9,"[18]" => 9,"[19]" => 9);
var_dump($arr);
$newarr=array_unique($arr);
var_dump($newarr);
?>
使用内置数组功能。
array_unique();
给你预期的结果。检查 link
好的,我得到了我想要的答案,感谢所有试图帮助我的人。
$str = Array('0' => 1,'1' => 2,'2' => 3,'3' => 3,'4' => 4,'5' => 5,'6' => 5,'7' => 6,'8' => 6,'9' => 6,'10' => 7,'11' => 8,'12' => 8,'13' => 8,'14' => 8,'15' => 9,'16' => 9,'17' => 9,'18' => 9,'19' => 9);
$flag = 0;
foreach($str as $key=>$value)
{
if($flag == $value)
{
unset($str[$key-1]);
}
$flag = $value;
}
echo "<pre>";
print_r($str);
我有一个这样的数组:
Array([0] => 1,[1] => 2,[2] => 3,[3] => 3,[4] => 4,[5] => 5,[6] => 5,[7] => 6,[8] => 6,[9] => 6,[10] => 7,[11] => 8,[12] => 8,[13] => 8,[14] => 8,[15] => 9,[16] => 9,[17] => 9,[18] => 9,[19] => 9)
但我想要的结果是这样的:
Array([0] => 1,[1] => 2,[3] => 3,[4] => 4,[6] => 5,[9] => 6,[10] => 7,[14] => 8,[19] => 9)
这不仅消除了相同数组的值,而且消除了看起来是相同值的最后一个索引/键的值的相同值。谁能帮帮我?
array_unique()
Takes an input array and returns a new array without duplicate values.
示例:
array_unique($your_array);
可以使用数组操作函数
array_unique($arr);
array_unique()
函数通过你可以得到数组的唯一值。
<?php
$data=Array(1,2,3,3,4,5,5,6,6,6,7,8,8,8,8,9,9,9,9);
echo '<pre>';
print_r($data);
$ans=array_unique($data);
print_r($ans);
echo '</pre>';
?>
<?php $arr=Array("[0]" => 1,"[1]" => 2,"[2]" => 3,"[3]" => 3,"[4]" => 4,"[5]" => 5,"[6]" => 5,"[7]" => 6,"[8]" => 6,"[9]" => 6,"[10]" => 7,"[11]" => 8,"[12]" => 8,"[13]" => 8,"[14]" => 8,"[15]" => 9,"[16]" => 9,"[17]" => 9,"[18]" => 9,"[19]" => 9);
var_dump($arr);
$newarr=array_unique($arr);
var_dump($newarr);
?>
使用内置数组功能。
array_unique();
给你预期的结果。检查 link
好的,我得到了我想要的答案,感谢所有试图帮助我的人。
$str = Array('0' => 1,'1' => 2,'2' => 3,'3' => 3,'4' => 4,'5' => 5,'6' => 5,'7' => 6,'8' => 6,'9' => 6,'10' => 7,'11' => 8,'12' => 8,'13' => 8,'14' => 8,'15' => 9,'16' => 9,'17' => 9,'18' => 9,'19' => 9);
$flag = 0;
foreach($str as $key=>$value)
{
if($flag == $value)
{
unset($str[$key-1]);
}
$flag = $value;
}
echo "<pre>";
print_r($str);