PHP删除重复的3d数组

时间:2015-04-11 16:21:14

标签: php arrays

我有一个三维数组,如下所示:

Array
(
[0] => Array
    (
        [id] => 7839253
        [companyInfo] => Array
            (
                [companyName] => UniqueName
                [orgNumber] => 32839434
                [companyText] => UniqueText
            )
    )

[1] => Array
    (
        [id] => 1729013
        [companyInfo] => Array
            (
                [companyName] => UniqueName
                [orgNumber] => 32839434
                [companyText] => UniqueText
            )
    )

[2] => Array
    (
        [id] => 8731121
        [companyInfo] => Array
            (
                [companyName] => UniqueName
                [orgNumber] => 32839434
                [companyText] => UniqueText
            )
    )
[3] => Array
    (
        [id] => 873112921
        [companyInfo] => Array
            (
                [companyName] => UniqueName
                [orgNumber] => 42119424
                [companyText] => UniqueText
            )
    )
)

我很难在orgNumber上删除这些匹配的数组。我试过这个:

$jsonresult = array_map("unserialize", array_unique(array_map("serialize", $jsonresult)));

任何包含orgnumber的多阵列,都应删除该公司的完整数组。不是最后一个,因为它有一个不同的orgNumber。创建这个:

Array
(
[0] => Array
    (
        [id] => 7839253
        [companyInfo] => Array
            (
                [companyName] => UniqueName
                [orgNumber] => 32839434
                [companyText] => UniqueText
            )
    )
[1] => Array
    (
        [id] => 873112921
        [companyInfo] => Array
            (
                [companyName] => UniqueName
                [orgNumber] => 42119424
                [companyText] => UniqueText
            )
    )
)

1 个答案:

答案 0 :(得分:1)

array_filter()看起来很明显,例如:

$currentOrgs = [];
$newArray = array_filter(
    $oldArray,
    function($value) use (&$currentOrgs){
        if (isset($currentOrgs[$value['companyInfo']['orgNumber']])) {
            return false;
        }
        $currentOrgs[$value['companyInfo']['orgNumber']] = true;
        return true;
    }
);