Home > Article > Backend Development > How to remove duplicate values from php multidimensional array
How to remove duplicate values from multi-dimensional arrays in php: 1. Use "array_map('serialize', $arr)" to convert the multi-dimensional array into a one-dimensional array in the form of a string; 2. Use array_unique() to remove Duplicate values in the one-dimensional array; 3. Reconvert the deduplicated one-dimensional array into a multi-dimensional array.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php multi-dimensional array removal Duplicate values
1. Implement function to remove duplicate values from multi-dimensional array
function array_unique_new($arr) { $t = array_map('serialize', $arr); //利用serialize()方法将数组转换为以字符串形式的一维数组 $t = array_unique($t); //去掉重复值 $new_arr = array_map('unserialize', $t); //然后将刚组建的一维数组转回为php值 return $new_arr; }
2. Array that needs to remove duplicate values
$arr = array( array('sup_name' => '上海', 'cn_name' => 'EthylAcetate', 'en_name' => '乙酸乙酯1', 'pinyin' => 'yisuanyizhi', 'pro_info' => '耗材', ), array('sup_name' => '上海2', 'cn_name' => 'EthylAcetate', 'en_name' => '乙酸乙酯2', 'pinyin' => 'yisuanyizhi', 'pro_info' => '耗材', ), array('sup_name' => '上海4', 'cn_name' => 'EthylAcetate', 'en_name' => '乙酸乙酯1', 'pinyin' => 'yisuanyizhi', 'pro_info' => '耗材', ), array('sup_name' => '上海', 'cn_name' => 'EthylAcetate', 'en_name' => '乙酸乙酯3', 'pinyin' => 'yisuanyizhi', 'pro_info' => '耗材', ), array('sup_name' => '上海1', 'cn_name' => 'EthylAcetate', 'en_name' => '乙酸乙酯4', 'pinyin' => 'yisuanyizhi', 'pro_info' => '耗材', ), array('sup_name' => '上海', 'cn_name' => 'EthylAcetate', 'en_name' => '乙酸乙酯3', 'pinyin' => 'yisuanyizhi', 'pro_info' => '耗材', ), array('sup_name' => '上海1', 'cn_name' => 'EthylAcetate', 'en_name' => '乙酸乙酯4', 'pinyin' => 'yisuanyizhi', 'pro_info' => '耗材', ), );
Look at the output:
3. Execute the test
$new_arr = array_unique_new($arr); echo '<pre/>'; print_r($new_arr);
Recommended learning: "PHP Video Tutorial》
The above is the detailed content of How to remove duplicate values from php multidimensional array. For more information, please follow other related articles on the PHP Chinese website!