Home > Article > Backend Development > Detailed explanation of the two-dimensional array deduplication function in PHP
we This article mainly introduces PHP to implement the two-dimensional array deduplication function, involving PHP's array traversal, judgment, setting and other related operating skills. It has certain reference value. Friends in need can refer to it
The details are as follows:
Double deduplication operation of two-dimensional array in php. For example, the records queried from the database are deduplicated based on a certain key.
The code is as follows:
/** * 删除二维数组中相同项的数据,(一般用于数据库查询结果中相同记录的去重操作) * * @param array $_2d_array 二维数组,类似: * $tmpArr = array( * array('id' => 1, 'value' => '15046f5de5bb708e'), * array('id' => 1, 'value' => '15046f5de5bb708e'), * ); * @param string $unique_key 表示上述数组的 "id" 键,或者 "value" 键 * * @return mixed */ function unique_2d_array_by_key($_2d_array, $unique_key) { $tmp_key[] = array(); foreach ($_2d_array as $key => &$item) { if ( is_array($item) && isset($item[$unique_key]) ) { if ( in_array($item[$unique_key], $tmp_key) ) { unset($_2d_array[$key]); } else { $tmp_key[] = $item[$unique_key]; } } } return $_2d_array; } //使用示例: $tmpArr = array( array('id' => 1, 'value' => '15046f5de5bb708e'), array('id' => 1, 'value' => '15046f5de5bb708e'), ); print_r(@unique_2d_array_by_key($tmpArr,id));
Running results:
Array ( [0] => Array ( [id] => 1 [value] => 15046f5de5bb708e ) )
Principle: Save the keys in the second-dimensional array that need to be deduplicated, traverse and compare the next set of data, if If the key values are the same, delete them.
The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
php implements adding values to all one-dimensional arrays in two-dimensional arrays
Method in php to add values to all one-dimensional arrays in two-dimensional array
The above is the detailed content of Detailed explanation of the two-dimensional array deduplication function in PHP. For more information, please follow other related articles on the PHP Chinese website!