通过值组合两个数组的巧妙方法

时间:2018-10-10 08:47:17

标签: php arrays

我遇到这样的情况:

//[itemId] => [agentId]

[123] => [1qa2ws]
[456] => [3ed4rf]

其他:

// array of agents with full objects inside

[0] => [id => 1qa2ws, ....]
[1] => [id => 3ed4rf, ....]

因此,现在我想以一种可以告诉我的方式将其组合起来:“好吧,如果agent数组中的ID与第一个数组的值相同,则将整个对象应用于它,而不是现在仅ID”。

我有一个“肮脏”的解决方案:

foreach ($agentIDs as &$agentID){
    foreach ($resolvedAgents as $agent){
        if($agent['accountId'] == $agentID){
            $agentID = $agent;
        }
    }
}

两个数组的顺序不必相同,因此第一个数组的第一个数组位置不必与agent数组中的第一个agent相同。

我想结束:

[123] => [id => 1qa2ws, ....]
[456] => [id => 3ed4rf, ....]

有解决方案吗?

4 个答案:

答案 0 :(得分:0)

array_combine呢?

$result = array_combine($array1, $array2)

PHPDoc

答案 1 :(得分:0)

您可以使用array_reduce

$a = array();
$a[123] = ['1qa2ws'];
$a[456] = ['3ed4rf'];

$b = array();
$b[0] = ['id' => '1qa2ws', 'other' => 'data'];
$b[1] = ['id' => '3ed4rf', 'other' => 'data'];
$b[2] = ['id' => 'av42sa', 'other' => 'data'];

$c = array_reduce($a, function ($carry, $item) use ($a, $b) {
    $itemId = array_search($item, $a);
    $agentId = array_values($item)[0];

    if (array_search($agentId, array_column($b, 'id')) !== false) {
        $carry[$itemId] = $b[array_search($agentId, array_column($b, 'id'))];
    }

    return $carry;
}, []);

答案 2 :(得分:0)

我实际上最终做到了,这是我满意的解决方案:

$agents = array_map(function($agent) use ($resolvedAgents){
    return $resolvedAgents[array_search($agent, array_column($resolvedAgents, 'accountId'))] ?: null;
}, $agentIDs);

从第二个数组开始,基本上从找到它的位置返回该项目。

答案 3 :(得分:0)

我认为您可以使用array_combinearray_column

$resolvedAgents = array_combine(array_column($resolvedAgents, 'id'), $resolvedAgents);

之后,$ resolvedAgents将变为:

[1qa2ws] => [id => 1qa2ws, ....]
[3ed4rf] => [id => 3ed4rf, ....]

而且您将拥有第一个数组:

// [itemId] => [agentId]
[123] => [1qa2ws]
[456] => [3ed4rf]

如果最后只需要一个数组,则:

$agents = array_map(function($agentId) use ($resolvedAgents) {
    return $resolvedAgents[$agentId] ?: null;
}, $agentIDs);

最后,您的代码将是:

$resolvedAgents = array_combine(array_column($resolvedAgents, 'id'), $resolvedAgents);
$agents = array_map(function($agentId) use ($resolvedAgents) {
    return $resolvedAgents[$agentId] ?: null;
}, $agentIDs);