将数组的每个键和值与另一个数组组合在一起

时间:2016-05-04 07:29:54

标签: php arrays for-loop foreach

我有这两个数组:

$arr1 = Array ( 600 => 580, 500 => 480, 100 => 80 ) <- always 3

$arr2 = Array ( 'filt' => grey, 'or' => 90 ) <- this array is dynamic

如何将第一个数组中的每个键和值与另一个数组合并?我的意思是,我需要:

$array = ( 600 => 580, 'filt' => grey, 'or' => 90 )
$array = ( 580 => 480, 'filt' => grey, 'or' => 90 )

先后for / foreach循环。我怎样才能做到这一点? 非常感谢,我是新的PHP ^^并抱歉我的英语:P

4 个答案:

答案 0 :(得分:0)

试试这个:

$arr1 = array( '600' => '580', '500' => '480', '100' => '80' ) ;
$arr2 = array( 'filt' => 'grey', 'or' => '90' );
$arra_new = array();
foreach($arr1 as $key=>$arr) {
  $temp = $arr2;
  $temp[$key] = $arr;
  $arra_new[] = $temp;
}
print '<pre>';print_r($arra_new);exit;

答案 1 :(得分:0)

使用array_walkarray_replace函数的解决方案:

$arr1 = Array(600 => 580, 500 => 480, 100 => 80);
$arr2 = Array('filt' => 'grey', 'or' => 90, 'and' => 150, 'if' => 10);
$combined = [];

array_walk($arr1, function($v, $k) use($arr2, &$combined) {
    $combined[] = array_replace([$k => $v], $arr2);
});

print_r($combined);

输出:

Array
(
    [0] => Array
        (
            [600] => 580
            [filt] => grey
            [or] => 90
            [and] => 150
            [if] => 10
        )

    [1] => Array
        (
            [500] => 480
            [filt] => grey
            [or] => 90
            [and] => 150
            [if] => 10
        )

    [2] => Array
        (
            [100] => 80
            [filt] => grey
            [or] => 90
            [and] => 150
            [if] => 10
        )
)

答案 2 :(得分:0)

尝试这种方法..

<?php 
$arr1 = array(600 => 580, 500 => 480, 100 => 80 );
$arr2 = array( 'filt' => 'grey', 'or' => 90 );

$newArray =array();
foreach($arr1 as $key =>$val)
{
    $temp =array();
    $temp[$key]= $val;
    $newArray[] =$temp+$arr2;
}

echo "<pre>"; print_r($newArray);
?>

这将输出:

Array
(
    [0] => Array
        (
            [600] => 580
            [filt] => grey
            [or] => 90
        )

    [1] => Array
        (
            [500] => 480
            [filt] => grey
            [or] => 90
        )

    [2] => Array
        (
            [100] => 80
            [filt] => grey
            [or] => 90
        )

)

答案 3 :(得分:0)

我认为你需要这个。只需循环遍历第一个数组,复制out数组中的第一个数组,并将循环数组的键值添加到out数组中。

  

如你所说:

$array = ( 600 => 580, 'filt' => grey, 'or' => 90 )
$array = ( 580 => 480, 'filt' => grey, 'or' => 90 )
     

我认为你每次都需要创建不同的数组。对于每一个   第一个数组的元素,你需要不同的数组作为输出。

$arr1 = array( "600" => 580, "500" => 480, "100" => 80 );
$arr2 = array( 'filt' => "grey", 'or' => 90 );

$out = array();
foreach($arr1 as $key => $value){
    $out = $arr2;
    $out[$key] = $value;

    print_r($out);
}

<强>结果

第一次迭代:

Array
(
    [filt] => grey
    [or] => 90
    [600] => 580
)

第二次迭代:

Array
(
    [filt] => grey
    [or] => 90
    [500] => 480
)

第三次迭代:

Array
(
    [filt] => grey
    [or] => 90
    [100] => 80
)