Example of implementing two-dimensional array deduplication function in PHP

高洛峰
Release: 2023-03-04 20:04:02
Original
1575 people have browsed it

The example of this article describes the implementation of two-dimensional array deduplication function in PHP. Share it with everyone for your reference, the details are as follows:

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, and delete them if the key values ​​are the same.

I hope this article will be helpful to everyone in PHP programming.

For more related articles on examples of PHP implementation of two-dimensional array deduplication function, please pay attention to 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