简体   繁体   English

将关联数组添加到另一个

[英]add associative array into another

i want to add one associative array into another but when i use array_push it overrides the value of previous one我想将一个关联数组添加到另一个中,但是当我使用 array_push 它会覆盖前一个的值

<?php
$tem = ["blue","ss"];
$len = count($tem);
print_r($len);
for($i=0;$i<$len;$i++){
    $data = [
        'code' => $tem[$i],
        'discount_type' => 'percent',   
    ];
    $a=array();
    $result[$i] =array_push($a,$data);
    print_r($a);
}
?>

and the output is output 是

2Array ( [0] => Array ( [code] => blue [discount_type] => percent ) ) 
 Array ( [0] => Array ( [code] => ss [discount_type] => percent ) )

The one problem is that you reset the $a array inside the loop, so it will only ever contain the last item.一个问题是您在循环内重置了$a数组,因此它只会包含最后一项。 Also, you don't assign the return from array_push() as it updates the array itself (but you never use $result[$i] anyway)...此外,您不会分配array_push()的返回值,因为它会更新数组本身(但您永远不会使用$result[$i] )...

So your code would end up something like..所以你的代码最终会像..

$tem = ["blue","ss"];
$len = count($tem);
print_r($len);
$a=array();
for($i=0;$i<$len;$i++){
    $data = [
            'code' => $tem[$i],
            'discount_type' => 'percent',
    ];
    array_push($a,$data);
}
print_r($a);

You can also shorten the code using a foreach loop and creating the array as you add it to the result...您还可以使用foreach循环缩短代码并在将其添加到结果时创建数组...

$tem = ["blue","ss"];
$a=array();
foreach ( $tem as $t )  {
    $a[] = [
        'code' =>  $t,
        'discount_type' => 'percent',
    ];
}
print_r($a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM