如何在 PHP 数组中找到所有结果,合并值,然后合并到另一个数组中

How can I find all results in a PHP array, merge values, and then merge into another array

使用 PHP,我有一个这样的数组:

数组 1

[
  {epid: "123", hash: "xxxxxx"},
  {epid: "456", hash: "xxxxxx"},
  {epid: "789", hash: "xxxxxx"},
  {epid: "123", hash: "xxxxxx"},
  {epid: "123", hash: "xxxxxx"},
]

然后,我有第二个这样的数组:

数组 2

[
  {epid: "123", name: "This is a title"},
  {epid: "456", name: "This is a title"},
  {epid: "789", name: "This is a title"}
]

我的目标是从数组 1 中获取所有 hash,并将它们添加到数组 2 中的适当记录中。在这个例子中,结果将是:

[
  {epid: "123", name: "This is a title", hash: [ xxxxxx, xxxxxx, xxxxxx ] },
  {epid: "456", name: "This is a title", hash: [ xxxxxx ] },
  {epid: "789", name: "This is a title", hash: [ xxxxxx ] }
]

我敢肯定这里有多个循环,但对于我来说,我无法绕过它。

您可以遍历第二个数组并使用 epid 查找第一个数组中的索引。然后对于找到的每个索引,将哈希添加到当前循环项:

$lookup = [
    ["epid" => "123", "hash" => "xxxxxxA"],
    ["epid" => "456", "hash" => "xxxxxxB"],
    ["epid" => "789", "hash" => "xxxxxxC"],
    ["epid" => "123", "hash" => "xxxxxxD"],
    ["epid" => "123", "hash" => "xxxxxxE"],
];

$db = [
    ["epid" => "123", "name" => "This is a title"],
    ["epid" => "456", "name" => "This is a title"],
    ["epid" => "789", "name" => "This is a title"]
];

foreach($db as $i => $el) {
    $keys = array_keys(array_column($lookup, 'epid'), $el["epid"]);
    foreach($keys as $key) {
        $db[$i]["hash"][] = $lookup[$key]["hash"];
    }
}

var_dump($db);

我假设您实际上没有 json 数组,而是 php 数组。如果没有,您必须先转换它们。 遍历 array2 中的每个条目并从 array1 中过滤出匹配项。如果完成,您可以轻松地通过 array_column 获取哈希并将它们添加到 array2.

$array1 = [
  ['epid' => "123", 'hash' => "xxxxxx"],
  ['epid' => "456", 'hash' => "xxxxxx"],
  ['epid' => "789", 'hash' => "xxxxxx"],
  ['epid' => "123", 'hash' => "xxxxxx"],
  ['epid' => "123", 'hash' => "xxxxxx"],
];

$array2 = [
  ['epid' => "123", 'name' => "This is a title"],
  ['epid' => "456", 'name' => "This is a title"],
  ['epid' => "789", 'name' => "This is a title"]
];

foreach ($array2 as $key => $data) {
    $matching = array_filter($array1, static fn($filterValue) => $data['epid'] === $filterValue['epid']);
    $array2[$key]['hash'] = array_column($matching, 'hash');
}

或者,您可以使用以下语句尽可能简短。它和上面的完全一样,但是更难读。

array_walk($array2, static fn(&$value) => $value['hash'] = array_column(array_filter($array1, static fn($filterValue) => $filterValue['epid'] === $value['epid']), 'hash'));