Detailed explanation of the two-dimensional array deduplication function in PHP

墨辰丷
Release: 2023-03-28 08:40:01
Original
1669 people have browsed it

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));
Copy after login

Running results:

Array ( [0] => Array ( [id] => 1 [value] => 15046f5de5bb708e ) )
Copy after login

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

php array implementation Detailed explanation of the method of merging the same key values ​​to generate a new two-dimensional array based on a certain key value

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!