1. 程式人生 > >PHP獲取二維陣列中指定Key的重複Value

PHP獲取二維陣列中指定Key的重複Value

<?php

/**
 * 判斷二維陣列中指定Key是否存在重複Value
 * @param array $arrInput 二維陣列
 * @param string $strKey 鍵名
 * @return bool
 */
function hasRepeatedValues($arrInput, $strKey)
{
    //引數校驗
    if (!is_array($arrInput) || empty($arrInput) || empty($strKey)) {
        return false;
    }

    //獲取陣列中所有指定Key的值,如果為空則表示鍵不存在
$arrValues = array_column($arrInput, $strKey); if (empty($arrValues)) { return false; } if (count($arrValues) != count(array_unique($arrValues))) { return true; } return false; } /** * 獲取二維陣列中指定Key的重複Value * @param array $arrInput 二維陣列 * @param string $strKey 鍵名 * @return
bool|string 重複的鍵值(以逗號分隔) */
function getRepeatedValues($arrInput, $strKey) { //引數校驗 if (!is_array($arrInput) || empty($arrInput) || empty($strKey)) { return false; } //獲取陣列中所有指定Key的值,如果為空則表示鍵不存在 $arrValues = array_column($arrInput, $strKey); if (empty($arrValues)) { return
false; } $arrUniqueValues = array_unique($arrValues); $arrRepeatedValues = array_unique(array_diff_assoc($arrValues, $arrUniqueValues)); return implode($arrRepeatedValues, ','); } //test $arrTest = [ [ 'id' => 1, 'name' => 'test1', ], [ 'id' => 1, 'name' => 'test2', ], [ 'id' => 1, 'name' => 'test3', ], [ 'id' => 2, 'name' => 'test4', ], [ 'id' => 2, 'name' => 'test5', ], [ 'id' => 3, 'name' => 'test6', ] ]; echo hasRepeatedValues($arrTest, 'id') . "\n"; echo getRepeatedValues($arrTest, 'id') . "\n";

感謝@qiaoweizhen提出了另一種更簡潔地實現方式~

function test($arr, $key)
{
    $arr = array_count_values(array_column($arr, $key));
    return array_filter($arr, function ($value) {
        if ($value > 1) {
            return $value;
        }
    });
}