色尼玛亚洲综合影院,亚洲3atv精品一区二区三区,麻豆freexxxx性91精品,欧美在线91

php 移除數組重復元素的一點說明

如:
復制代碼 代碼如下:
$test_array=array(1,2,3,4,4,5,5,6);
$test_array_unique=array_unique($test_array);
print_r($test_array_unique);
$test_array=array(1,2,3,4,4,5,5,6);
$test_array_unique=array_unique($test_array);
print_r($test_array_unique);
但是至此,不要粗心,事還沒結束。細心的看你會發現經管重復的元素被移除了,但是剩下來這些元素的索引沒有變化,這樣的話如果用for循環調用這個數組元素的時候就會發生錯誤了,因為for循環的時候是按照數字遞增,而且大多數人用的是count($test_array_unique)來獲得數組的大小,這樣就會造成一些元素被遺漏;
復制代碼 代碼如下:
$test_array=array(1,2,3,4,4,5,5,6);
$test_array_unique=array_unique($test_array);
for($i=0;$i<count($test_array_unique);$i++)
{
echo $test_array_unique[$i];
}
$test_array=array(1,2,3,4,4,5,5,6);
$test_array_unique=array_unique($test_array);
for($i=0;$i<count($test_array_unique);$i++)
{
echo $test_array_unique[$i];
}
這樣你不會看到元素6被輸出,因為6的索引是8,處理前的數組和處理后的數組索引沒有任何改變;
解決辦法:
當然,這里解決辦法太多了,我介紹的只是一種我覺得比較簡單的方法,那就是函數array_values,array_values是返回數組的值,跟索引沒有關系,這樣處理后會形成一個新的數組,嚴格按照數字遞增的索引,這樣再使用for循環輸出邊一切OK了!
復制代碼 代碼如下:
$test_array=array(1,2,3,4,4,5,5,6);
$test_array_unique=array_values(array_unique($test_array));
for($i=0;$i<count($test_array_unique);$i++)
{
echo $test_array_unique[$i];
}

php技術php 移除數組重復元素的一點說明,轉載需保留來源!

鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。

主站蜘蛛池模板: 新建县| 易门县| 新竹市| 高邑县| 龙门县| 新蔡县| 兰溪市| 宜良县| 烟台市| 龙胜| 洛扎县| 栾川县| 墨脱县| 米脂县| 邵东县| 西吉县| 牙克石市| 梅河口市| 太仆寺旗| 卫辉市| 美姑县| 巴林右旗| 扎兰屯市| 天镇县| 望奎县| 吉林省| 乌什县| 襄樊市| 淮南市| 柞水县| 绥棱县| 那曲县| 泰兴市| 富顺县| 东辽县| 固镇县| 罗田县| 安丘市| 肥东县| 林口县| 阜城县|