PHP Implementation of One Dimensional Array and Two Dimensional Array Duplicate Removal Function Example

  • 2021-10-11 17:53:32
  • OfStack

This paper describes the implementation of 1-dimensional array and 2-dimensional array de-duplication function by PHP. Share it for your reference, as follows:

Removal of duplicates from arrays

Duplicates of 1-dimensional arrays:

Use array_unique Function can be used as follows:


<?php
  $aa=array("1","2","3","3","2","watermalon");
  $bb=array_unique($aa);
  print_r($bb);
?>

The results are as follows:

Array ( [0] = > 1 [1] = > 2 [2] = > 3 [5] = > watermalon )

Duplicates of 2-dimensional arrays:

For 2-D arrays, we discuss them in two situations, one is because the value of a 1 key name cannot be repeated, and duplicate items are deleted; The other is to delete duplicates because the internal 1-dimensional arrays cannot be exactly the same. Here is an example:

Delete duplicates because the value of a 1 key name cannot be duplicated


<?php
function assoc_unique($arr, $key)
{
  $tmp_arr = array();
  foreach($arr as $k => $v)
  {
    if(in_array($v[$key], $tmp_arr))// Search $v[$key] Whether it is in $tmp_arr Array, if it exists, returns true
    {
     unset($arr[$k]);
    }
    else {
     $tmp_arr[] = $v[$key];
    }
  }
  sort($arr); //sort Function to sort an array 
  return $arr;
}
$aa = array(
  array('shopId' => 1),
  array('shopId' => 1),
  array('shopId' => 2),
  array('shopId' => 2)
);
$key = 'id';
$result = assoc_unique($aa, $key);
print_r($result);
?>

The result is displayed as follows:

Array ( [0] = > Array ( [shopId] = > 1 ) [1] = > Array ( [shopId] = > 2 ))

PS: This site also has two relatively simple and practical online text to repeat tools, recommended for everyone to use:

Online Duplicate Removal Tool:
http://tools.ofstack.com/code/quchong

Online text de-duplication tool:
http://tools.ofstack.com/aideddesign/txt_quchong

For more readers interested in PHP related content, please check the special topics of this site: "PHP Array (Array) Operation Skills Encyclopedia", "PHP Common Traversal Algorithms and Skills Summary", "php String (string) Usage Summary", "php Common Functions and Skills Summary", "PHP Error and Exception Handling Methods Summary", "PHP Basic Grammar Introduction Course", "php Object-Oriented Programming Introduction Course" and "PHP Mathematical Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: