我在foreach循环之外声明了一个数组,我用它来为数组添加值。现在,它在每个循环期间覆盖数组中的值。目标是不覆盖但是将值附加到数组,因此当foreach循环完成时,我将获得完整的值而不是最后一个循环中的值。这是示例
$vars = array(
'year' => null,
'make' => null,
'model' => null
);
foreach (){
$year = array(
'2000',
'2001',
'2002'
);
$make = array('honda'); // only 1 value
$model = array('accord'); // only 1 value
// do something here to append $year, $make, $model to the correct key in $vars
}
所以结果应该是这样的
$vars = array
(
'year' => array('2000','2001','2002,'2003','2004','2005','2006'),
'make' => array('honda','toyota','nissan'),
'model' => array('accord','camery','altima')
)
也许在foreach的某个地方检查并避免插入重复值会很好。例如......没有重复的年份,品牌和型号。
答案 0 :(得分:2)
尝试 -
$vars['year'] = array_merge($var['year'], $year);
与make
相同model
。
答案 1 :(得分:0)
试试这个
foreach (){
$year = array('2000','2001','2002');
$make = array('honda');
$model = array('accord');
array_push($vars['year'],$year);
array_push($vars['make'],$make);
array_push($vars['model'],$model);
}
答案 2 :(得分:0)
你没有一个公共参数来在一个foreach()循环中插入所有参数。像这样的更多循环
$vars = array(
'year' => null,
'make' => null,
'model' => null
);
$year = array(
'2000',
'2001',
'2002'
);
$make = array('honda'); // only 1 value
$model = array('accord'); // only 1 value
foreach ($year as $years) {
$vars['year'][] = $years;
}
foreach ($make as $makes) {
$vars['make'][] = $makes;
}
foreach ($model as $models) {
$vars['model'][] = $models;
}