php 數組去重 (一維數組與二維數組)


數組中重復項的去除

一維數組的重復項

       使用array_unique函數即可,使用實例如下:

               <?php
                   $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 ) 。

二維數組的重復項

      對於二維數組咱們分兩種情況討論,一種是因為某一鍵名的值不能重復,刪除重復項;另一種因為內部的一維數組不能完全相同,而刪除重復項,下面舉例說明:

            ㈠因為某一鍵名的值不能重復,刪除重復項

           <?php
            function assoc_unique($arr, $key)
             {
               $tmp_arr = array();
               foreach($arr as $k => $v)
              {
                 if(in_array($v[$key], $tmp_arr))//搜索$v[$key]是否在$tmp_arr數組中存在,若存在返回true
                {
                   unset($arr[$k]);
                }
              else {
                  $tmp_arr[] = $v[$key];
                }
              }
            sort($arr); //sort函數對數組進行排序
            return $arr;
            }

            $aa = array(
            array('id' => 123, 'name' => '張三'),
            array('id' => 123, 'name' => '李四'),
            array('id' => 124, 'name' => '王五'),
            array('id' => 125, 'name' => '趙六'),
            array('id' => 126, 'name' => '趙六')
            );
            $key = 'id';
            assoc_unique(&$aa, $key);
            print_r($aa);
            ?>

      顯示結果為:Array ( [0] => Array ( [id] => 123 [name] => 張三 ) [1] => Array ( [id] => 124 [name] => 王五 ) [2] => Array ( [id] => 125 [name] => 趙六 ) [3] => Array ( [id] => 126 [name] => 趙六 ) )

        ㈡因內部的一維數組不能完全相同,而刪除重復項

            <?php
            function array_unique_fb($array2D){
                 foreach ($array2D as $v){
                     $v = join(",",$v); //降維,也可以用implode,將一維數組轉換為用逗號連接的字符串
                     $temp[] = $v;
                 }
                 $temp = array_unique($temp);    //去掉重復的字符串,也就是重復的一維數組
                foreach ($temp as $k => $v){
                    $temp[$k] = explode(",",$v);   //再將拆開的數組重新組裝
                }
                return $temp;
            }

            $aa = array(
            array('id' => 123, 'name' => '張三'),
            array('id' => 123, 'name' => '李四'),
            array('id' => 124, 'name' => '王五'),
            array('id' => 123, 'name' => '李四'),
            array('id' => 126, 'name' => '趙六')
            );
            $bb=array_unique_fb($aa);
            print_r($bb)
            ?>

          顯示結果:Array ( [0] => Array ( [0] => 123 [1] => 張三 ) [1] => Array ( [0] => 123 [1] => 李四 ) [2] => Array ( [0] => 124 [1] => 王五 ) [4] => Array ( [0] => 126 [1] => 趙六 ) )  

轉載自:http://www.cnblogs.com/srsee/archive/2013/05/09/srsee.html


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: