我有以下数组:
最低值:
[2006] => 117
[2007] => 117
[2008] => 117
[2009] => 117
[2010] => 117
[2011] => 117
[2012] => 118
[2013] => 132
平均:
[2006] => 170
[2007] => 174
...
[2013] => 166
最大值:
[2006] => 291
[2007] => 630
...
[2013] => 246
如何合并它们,以便我有以下数组与子数组:
[2006] => array (117, 170, 291),
[2007] => array (117, 174, 630),
...
[2013] => array (132, 166, 246)
没有子阵列的解决方案也是一个很好的解决方案。这样的事情也可以解决问题:
[2006] => [117, 170, 291]
[2007] => [117, 174, 630]
...
[2013] => [132, 166, 246]
非常感谢提前!
答案 0 :(得分:1)
对数组名称做出了假设:
$new=array();
foreach($min as $k=>$v){
$new[$k]=array($v,$average[$k],$max[$k]);
}
并不真正理解“没有子阵列的解决方案”的意思 - 你想要一个字符串还是?
编辑字符串创建
$new='';
foreach($min as $k=>$v){
$new.='['.$v.','.$average[$k].','.$max[$k].'],';
}
$new=rtrim($new,',');//remove last comma
答案 1 :(得分:0)
它非常简单,只需编写一个foreach循环,循环遍历其中一个数组,我在这里使用$ mins数组。
然后从每个其他数组中获取等效数据,并使用key作为新数组的键将它们全部添加到新数组中。
$mins = array(2006 => 117, 2007 => 117, 2008 => 117,
2009 => 117, 2010 => 117, 2011 => 117,
2012 => 118, 2013 => 132);
$avgs = array(2006 => 170, 2007 => 174, 2008 => 169,
2009 => 179, 2010 => 180, 2011 => 181,
2012 => 182, 2013 => 183);
$maxs = array(2006 => 217, 2007 => 233, 2008 => 322,
2009 => 215, 2010 => 216, 2011 => 217,
2012 => 231, 2013 => 232);
$newArray = array();
foreach( $mins as $year => $min ) {
$newArray[$year] = array( $min, $avgs[$year], $maxs[$year] );
}
print_r( $newArray );
输出是: -
Array
(
[2006] => Array
(
[0] => 117
[1] => 170
[2] => 217
)
[2007] => Array
(
[0] => 117
[1] => 174
[2] => 233
)
[2008] => Array
(
[0] => 117
[1] => 169
[2] => 322
)
[2009] => Array
(
[0] => 117
[1] => 179
[2] => 215
)
[2010] => Array
(
[0] => 117
[1] => 180
[2] => 216
)
[2011] => Array
(
[0] => 117
[1] => 181
[2] => 217
)
[2012] => Array
(
[0] => 118
[1] => 182
[2] => 231
)
[2013] => Array
(
[0] => 132
[1] => 183
[2] => 232
)
)
使用新的数组语法,它将是
$mins = [2006 => 117, 2007 => 117, 2008 => 117,
2009 => 117, 2010 => 117, 2011 => 117,
2012 => 118, 2013 => 132];
$avgs = [2006 => 170, 2007 => 174, 2008 => 169,
2009 => 179, 2010 => 180, 2011 => 181,
2012 => 182, 2013 => 183];
$maxs = [2006 => 217, 2007 => 233, 2008 => 322,
2009 => 215, 2010 => 216, 2011 => 217,
2012 => 231, 2013 => 232];
$newArray = [];
foreach( $mins as $year => $min ) {
$newArray[$year] = [ $min, $avgs[$year], $maxs[$year] ];
}
print_r( $newArray );
如果你想把结果作为一个字符串数组,就像这样改变它
foreach( $mins as $year => $min ) {
$newArray[$year] = sprintf('[%d,%d,%d]', $min, $avgs[$year], $maxs[$year]);
}
print_r( $newArray );
给出这个结果
Array
(
[2006] => [117,170,217]
[2007] => [117,174,233]
[2008] => [117,169,322]
[2009] => [117,179,215]
[2010] => [117,180,216]
[2011] => [117,181,217]
[2012] => [118,182,231]
[2013] => [132,183,232]
)