dopa53272
2017-03-03 06:27
浏览 43
已采纳

基于多个键从多维数组中删除重复项

Sorry if this was asked before, but I searched a lot and couldn't find a solution. I've been trying to solve this problem for a while now, and couldn't write the function for it.

I have an array like that:

    $numbers = array(
        array("tag" => "developer", "group" => "grp_1", "num" => "123123"),
        array("tag" => "developer", "group" => "grp_2", "num" => "111111"),
        array("tag" => "student", "group" => "grp_1", "num" => "123123"),
        array("tag" => "student", "group" => "grp_2", "num" => "123123"),
        array("tag" => "developer", "group" => "grp_3", "num" => "111111"),
    );

I need to write a function, that removes the duplicates off this array, based on multiple keys, so my function call should look something like that:

unique_by_keys($numbers, array("num","group"));

In other terms, one number can't be in the same group more than once.

After calling unique_by_keys() by array should be like that:

    $numbers = array(
        array("tag" => "developer", "group" => "grp_1", "num" => "123123"),
        array("tag" => "developer", "group" => "grp_2", "num" => "111111"),
        array("tag" => "student", "group" => "grp_2", "num" => "123123"),
        array("tag" => "developer", "group" => "grp_3", "num" => "111111"),
    );

I'd appreciate if you could help me find a solution, or lead me to the correct way of thinking. Thanks!


SOLUTION: I was able to find a solution, by writing the following function: ( I wrote it in a way that accepts many forms of $haystack arrays )

function unique_by_keys($haystack = array(), $needles = array()) {
    if (!empty($haystack) && !empty($needles)) {
        $_result = array();
        $result = array();
        $i = 0;
        foreach ($haystack as $arrayObj) {
            if (is_array($arrayObj)) {
                $searchArray = array();
                foreach ($needles as $needle) {
                    if (isset($arrayObj[$needle])) {
                        $searchArray[$needle] = $arrayObj[$needle];
                    }
                }
                if (!in_array($searchArray, $_result)) {
                    foreach ($arrayObj as $key => $value) {
                        if (in_array($key, $needles)) {
                            $_result[$i][$key] = $value;
                        }
                    }
                    $result[] = array_merge($_result[$i], $arrayObj);
                }
            } else {
                $result[] = $arrayObj;
            }
            $i++;
        }
        return $result;
    }
}

Thanks for everyone that replied!

3条回答 默认 最新

相关推荐 更多相似问题