Home>Article>Backend Development> PHP array_unique implements two-dimensional array deduplication
array_unique
The function can be used to handle duplicates. It has this function. Let’s take a look at the use of array_unique in PHP Two-dimensional array deduplication processing example.
php version 5.2.9 adds array_unique support for multi-dimensional arrays. When processing multi-dimensional arrays, you need to set sort_flags
Parameters
Duplication of one-dimensional arrays Item:
Just use the array_unique function. The usage example is as follows:
The code is as follows
The result is as follows:
Array ( [0] => apple [1] => banana [2] => pear [4] => wail [5] => watermalon )
Two-dimensional array deduplication Item
The code is as follows
For example:
$result = array(
0=>array('a'=>1,'b '=>'Hello'),
1=>array('a'=>1,'b'=>'other'),
2=>array('a'= >1,'b'=>'other'),
);
is processed into
$result = array(
0=>array('a'=>1,'b'=>'Hello'),
1=>array('a'=>1,'b'=>' other')
);
Usage method
array_unique($result, SORT_REGULAR);
Duplicates of two-dimensional arrays:
For two-dimensional arrays, we will discuss it in two situations. One is because the value of a certain key name cannot be repeated, and duplicates are deleted; the other is because the internal one-dimensional The arrays cannot be exactly the same, and duplicates are deleted. The following is an example:
Because the value of a certain key name cannot be duplicated, duplicates are deleted
The PHP code is as follows
$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); ?>
The displayed result is:
Array ( [0] => Array ( [id] => 123 [name] => 张三 ) [1] => Array ( [id] => 124 [name] => 王五 ) [2] => Array ( [id] => 125 [name] => 赵六 ) [3] => Array ( [id] => 126 [name] => 赵六 ) )
Because the internal one-dimensional arrays cannot be exactly the same, and duplicates are deleted
The code is as follows
$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) ?>
The displayed result is:
Array ( [0] => Array ( [0] => 123 [1] => 张三 ) [1] => Array ( [0] => 123 [1] => 李四 ) [2] => Array ( [0] => 124 [1] => 王五 ) [4] => Array ( [0] => 126 [1] => 赵六 ) )
Related learning recommendations:PHP programming from entry to proficiency
The above is the detailed content of PHP array_unique implements two-dimensional array deduplication. For more information, please follow other related articles on the PHP Chinese website!