PHP推送值数组从一个到另一个

时间:2017-05-14 17:45:41

标签: php arrays

我有两个数组,想要得到一个

//first

        [0] => Array (
        [drink] => A
        [litres] => 100.05
        )
    [1] => Array (
        [drink] => B
        [litres] => 3943
        )
    [2] => Array (
        [drink] => C
        [litres] => 1.46
        )


  //second      

        [0] => 22
        [1] => 12
        [2] => 16

结果应为:

[0] => Array (
    [drink] => A
    [litres] => 100.05
    [price] => 22
    )
[1] => Array (
    [drink] => B
    [litres] => 3943
    [price] => 12
    )
[2] => Array (
    [drink] => C
    [litres] => 1.46
    [price] => 16
    )

我尝试使用循环,合并等所有我应该在这个网站上找到。但我不明白。

foreach ($arr as $array2) {
    $array1[] = array( 'price' => $array2 );
}

print_r($array1);

我不明白

提前致谢

3 个答案:

答案 0 :(得分:0)

使用array_maparray_merge函数的简短解决方案:

$result = array_map(function($a, $b){
    return array_merge($a, ['price'=>$b]);
}, $arr1, $arr2);

print_r($result);

输出:

Array
(
    [0] => Array
        (
            [drink] => A
            [litres] => 100.05
            [price] => 22
        )

    [1] => Array
        (
            [drink] => B
            [litres] => 3943
            [price] => 12
        )

    [2] => Array
        (
            [drink] => C
            [litres] => 1.46
            [price] => 16
        )
)

答案 1 :(得分:0)

$result = array_map(function($i, $j) { return array_merge($i, array('price'=>$j)); }, 
                    $arr1, $arr2);

<强> demo on eval.in

答案 2 :(得分:0)

其他答案都是正确的方法,我只想说明如何使用foreach()循环:

代码:

$a=[
    ["drink"=>"A","litres"=>100.05],
    ["drink"=>"B","litres"=>3943],
    ["drink"=>"C","litres"=>1.46]
   ];
$b=[22,12,16];

foreach($a as $i=>$subarray){
    $a[$i]["price"]=$b[$i];
}
var_export($a);

这种方法不是单行,但运行速度稍快,因为它的函数调用次数较少,大多数人也会更容易阅读。 (虽然我承认 - 我倾向于单行)注意,我的方法没有声明一个新的结果变量,它只是扩展了第一个数组。

输出(根据需要):

array (
  0 => 
  array (
    'drink' => 'A',
    'litres' => 100.05,
    'price' => 22,
  ),
  1 => 
  array (
    'drink' => 'B',
    'litres' => 3943,
    'price' => 12,
  ),
  2 => 
  array (
    'drink' => 'C',
    'litres' => 1.46,
    'price' => 16,
  ),
)