它很簡單,只寫了foreach循環,在循環遍歷數組中的一個,我這裏使用的$分鐘陣列。
然後從每個其他數組中獲取等價數據,並將它們全部添加到新數組中,並使用鍵作爲新數組的鍵。
$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]
)
foreach循環,使用鍵 – 2014-10-02 22:25:46