代码之家  ›  专栏  ›  技术社区  ›  Norgul

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

  •  1
  • Norgul  · 技术社区  · 6 年前

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

    // array of agents with full objects inside
    
    [0] => [id => 1qa2ws, ....]
    [1] => [id => 3ed4rf, ....]
    

    所以现在我想用一种方式来组合它,我可以告诉“好的,如果代理数组的ID与第一个数组的值相同,那么应用整个对象,而不是现在的ID”。

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

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

    最后我想说:

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

    有没有更干净的解决办法?

    4 回复  |  直到 6 年前
        1
  •  0
  •   Lithilion    6 年前

    那怎么办 array_combine

    $result = array_combine($array1, $array2)
    

    PHPDoc

        2
  •  0
  •   BritishWerewolf TalOrlanczyk    6 年前

    你可以用 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;
    }, []);
    
        3
  •  0
  •   sklwebdev    6 年前

    array_combine array_column :

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

    在此之后,$resolvedAgent将成为:

    [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);
    
        4
  •  0
  •   Norgul    6 年前

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

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