交叉比较两个数组元素

时间:2016-07-07 12:18:53

标签: php arrays

经过大量的API调用和循环后,我创建了一个数组。该数组采用以下形式

2 => array:3 [▼
    "someInfo" => array:1 [▶]
    "existingIDs" => array:1 [▼
      0 => array:1 [▼
        "id" => "123456"
      ]
    ]
    "idList" => array:2 [▼
      0 => array:1 [▼
        "id" => "123456"
      ]
      1 => array:1 [▼
        "id" => "777564"
      ]
    ]
]

我感兴趣的部分是现有的ID和idList。问题是某些ID出现在两个数组元素中,因此在上面的示例中,id 123456出现在两者中。 我需要做的是交叉比较这两个元素,并可能创建一个具有唯一ID的新元素。所以上面的例子可能变成这样的东西

2 => array:3 [▼
    "someInfo" => array:1 [▶]
    "existingIDs" => array:1 [▼
      0 => array:1 [▼
        "id" => "123456"
      ]
    ]
    "idList" => array:2 [▼
      0 => array:1 [▼
        "id" => "123456"
      ]
      1 => array:1 [▼
        "id" => "777564"
      ]
    ]
    "uniqueList" => array:2 [
      0 => array:1 [
        "id" => "123456"
      ]
      1 => array:1 [
        "id" => "777564"
      ]
    ]
]

如何才能实现这样的目标?

由于

1 个答案:

答案 0 :(得分:2)

array_column(自PHP 5.5以来可用),array_mergearray_unique函数使用以下方法:

$arr =  [
    "someInfo" => [],
    "existingIDs" => [
        ["id" => "123456"]
    ],
    "idList" => [
      ["id" => "123456"],
      ["id" => "777564"],
      ["id" => "777564"]
    ]
];

$all_ids = array_merge(array_column($arr['existingIDs'], 'id'), array_column($arr['idList'], 'id'));
$arr['uniqueList'] = array_unique($all_ids);

print_r($arr);

输出:

Array
(
    [someInfo] => Array
        (
        )

    [existingIDs] => Array
        (
            [0] => Array
                (
                    [id] => 123456
                )
        )

    [idList] => Array
        (
            [0] => Array
                (
                    [id] => 123456
                )

            [1] => Array
                (
                    [id] => 777564
                )

            [2] => Array
                (
                    [id] => 777564
                )
        )

    [uniqueList] => Array
        (
            [0] => 123456
            [2] => 777564
        )
)