使用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中获取所有散列,并将它们添加到数组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'));