将一个数组值添加到另一个

时间:2012-08-25 03:38:18

标签: php arrays

这是数组#1

Array
(
    [0] => Array
        (
            [first] => LightSpeed
            [last] => Administrator
        )

    [1] => Array
        (
            [first] => Tyler
            [last] => Nichol
        )

这是数组#2

Array
(
    [I-10] => Array
        (
            [user] => 2
            [total] => 46.64
        )

    [I-11] => Array
        (
            [user] => 2
            [total] => -46.64
        )

我只想添加[total] => $ value到第一个数组,看起来像。

Array
(
    [0] => Array
        (
            [first] => LightSpeed
            [last] => Administrator
            [total] => 46.64
        )

    [1] => Array
        (
            [first] => Tyler
            [last] => Nichol
            [total] => -46.64
        )

很确定它是array_push但不确定如何循环它。有什么建议?谢谢!

3 个答案:

答案 0 :(得分:0)

技术有点低,但我只是遍历你的阵列并插入总项目。假设您只是匹配数组中项目位置的第二个数组:

$vals = array_values($arr2);
foreach($arr1 as $i=>$item) {
    $arr1[$i]['total'] = $vals[$i]['total'];
}

答案 1 :(得分:0)

你不必一直循环.. array_merge可以做到这一点

function superMerge($a, $b) {
    $a['total'] = $b['total'];
    return $a;
}

$array1 = array(0 => Array("first" => "LightSpeed","last" => "Administrator"),1 => Array("first" => "Tyler","last" => "Nichol"));
$array2 = array("I-10" => Array("user" => 2,"total" => 46.64),"I-11" => Array("user" => 2,"total" => - 46.64));

var_dump(array_map("superMerge", $array1, $array2));

输出

array
  0 => 
    array
      'first' => string 'LightSpeed' (length=10)
      'last' => string 'Administrator' (length=13)
      'total' => float 46.64
  1 => 
    array
      'first' => string 'Tyler' (length=5)
      'last' => string 'Nichol' (length=6)
      'total' => float -46.64

答案 2 :(得分:0)

您的数组格式不正确,所以我在答案中已经这样做了。您可能想要更新您的问题

<?php
$arr1 = Array
(
     Array
        (
            'first' => 'LightSpeed',
            'last' => 'Administrator'
        ),

     Array
        (
            'first' => 'Tyler',
            'last' => 'Nichol'
        )
);

$arr2 = Array
(
    'I-10' => Array
        (
            'user' => 2,
            'total' => 46.64
        ),

    'I-11' => Array
        (
            'user' => 2,
            'total' => -46.64
        )
);


$n = count($arr1);
$i = 0;
foreach($arr2 as $arr)
{
   $arr1[$i]['total'] = $arr['total'];
   $i++;
}

var_dump($arr1);
?>

var_dump

的结果
array
  0 => 
    array
      'first' => string 'LightSpeed' (length=10)
      'last' => string 'Administrator' (length=13)
      'total' => float 46.64
  1 => 
    array
      'first' => string 'Tyler' (length=5)
      'last' => string 'Nichol' (length=6)
      'total' => float -46.64