在大型数据集上组合两个数组键

时间:2016-12-08 13:49:04

标签: php arrays

我有这个数组:

Array
(
    [0] => Array
        (
            [id] => 1
            [franchise_id] => A123
            [brand_id] => 26
            [hold_amount] => null
        )

    [1] => Array
        (
            [id] => 2
            [franchise_id] => A123
            [brand_id] => 54
            [hold_amount] => null
        )
)

我有另一个阵列: -

Array
(
    [0] => stdClass Object
        (
            [amount_to_settle] => 15.04
            [franchise_id] => A123
            [brand_id] => 26
        )

    [1] => stdClass Object
        (
            [amount_to_settle] => 45.53
            [franchise_id] => A123
            [brand_id] => 54
        )

)

我需要将两者结合起来,以便得到这样的最终数组:

id
franchise_id
brand_id
hold_amount
amount_to_settle

如何在数据集巨大的情况下以优化的方式完成

3 个答案:

答案 0 :(得分:1)

您可以使用array_map()。

 $value = array_map(null, $array1, $array2);
 print_r($value);

以下是参考http://php.net/manual/en/function.array-map.php

答案 1 :(得分:0)

  

您可以使用数组合并功能并避免std类obj错误遵循格式

$array1 = json_encode(json_decode(Array
(
    [0] => Array
        (
            [id] => 1
            [franchise_id] => A123
            [brand_id] => 26
            [hold_amount] => null
        )

    [1] => Array
        (
            [id] => 2
            [franchise_id] => A123
            [brand_id] => 54
            [hold_amount] => null
        )
)));

$array2 = json_encode(json_decode(Array
(
    [0] => stdClass Object
        (
            [amount_to_settle] => 15.04
            [franchise_id] => A123
            [brand_id] => 26
        )

    [1] => stdClass Object
        (
            [amount_to_settle] => 45.53
            [franchise_id] => A123
            [brand_id] => 54
        )

)));

print_r(array_unique(array_merge($array1,$array2), SORT_REGULAR));

答案 2 :(得分:0)

你可以在foreach()循环中执行此操作。

<强>循环

$newArray; //Store in here.


foreach($arrayOne as $k=>$v) {

    $key = array_search($v["brand_id"], array_column($arrayTwo, 'brand_id'));

    $newArray [] = [

        "id" => $v["id"], 
        "franchise_id" => $v["franchise_id"],
        "brand_id" => $v["brand_id"],
        "hold_amount" => $v["hold_amount"],
        "amount_to_settle" => $arrayTwo[$key]['amount_to_settle'],

    ] ;

}

var_dump($newArray);;

<强>输出

array(2) {

    [0] => array(5) {
        ["id"] => int(1)
        ["franchise_id"] => string(4) "A123"
        ["brand_id"] => int(26)
        ["hold_amount"] => NULL
        ["amount_to_settle"] => float(15.04)

    }[1] => array(5) {

        ["id"] => int(2)
        ["franchise_id"] => string(4) "A123"
        ["brand_id"] => int(54)
        ["hold_amount"] => NULL
        ["amount_to_settle"] => float(45.53)

    }
}

修改

没有意识到你的密钥会不同步。现在,它使用array_search()array_column()来匹配brand_id$arrayOne$arrayTwo的值。可能值得添加一个条件,以确保如果找不到匹配,它不会中断,但这将有效,尽管计数不同步。