首页 > 解决方案 > 如何通过在 php 中映射值来组合两个数组?

问题描述

我有两个数组 $a 和 $b

$a = [
    '0' => [
        'name'=>'Apple',
        'id' => 1
    ],
    '1' => [
        'name'=>'Banana',
        'id' => 2
    ],
    '2' => [
        'name' => 'orange',
        'id' => 3
    ]
];

$b = [
    '0' => [
        'price'=> 20,
        'a_id' => 2
    ],
    '1' => [
        'price'=> 10,
        'a_id' => 3
    ],
    '3' => [
        'price'=> 30,
        'a_id' => 1
    ]
];

我正在尝试使用 id(array $a), a_id (array $b) 映射创建另一个数组,我的输出看起来像

$a = [
    '0' => [
        'id' => 1
        'name'=>'Apple',
        'price' => 30
    ],
    '1' => [
        'id' => 2
        'name'=>'Banana',
        'price' => 20
    ],
    '2' => [
         'id' => 3
         'name' => 'orange',
         'price' => 10
    ]
];

我试过数组映射

$combined = array_map(null,$a,$b);

但是这个结果不是我想要的结果。如何在匹配后将我的第一个数组映射到第二个数组$a['id'] = $b['a_id']

标签: phparrays

解决方案


这应该有效,如果数组 $b 中的项目没有价格,则将添加默认价格 0。

<?php

$result = [];

$t = array_column($b, 'a_id');

foreach($a as $k => $v) {
    
    $index = array_search($v['id'], $t);
    $v['price'] = $index !== FALSE ? $b[$index]['price'] : 0;
    $result[] = $v;

}

print_r($result);

?>

结果:

(
    [0] => Array
        (
            [name] => Apple
            [id] => 1
            [price] => 30
        )

    [1] => Array
        (
            [name] => Banana
            [id] => 2
            [price] => 20
        )

    [2] => Array
        (
            [name] => orange
            [id] => 3
            [price] => 10
        )
)

推荐阅读