0

这是数组#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 但不知道如何循环它。有什么建议么?谢谢!

4

3 回答 3

0

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

$vals = array_values($arr2);
foreach($arr1 as $i=>$item) {
    $arr1[$i]['total'] = $vals[$i]['total'];
}
于 2012-08-25T04:03:30.443 回答
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
于 2012-08-25T04:04:01.400 回答
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
于 2012-08-25T04:16:15.140 回答