我有一个数组想要更改用于不同目的的数据格式。以下代码中的示例有很多季节与链接&每个季节都有一年。所以我想在每年下索引这些数据。 我目前的数组:
$infoArray =array(
array(
'season'=>'winter 2014',
'link'=>'link1'
),
array(
'season'=>'summer 2013',
'link'=>'link2'
),
array(
'season'=>'fall 2012',
'link'=>'link3'
),
array(
'season'=>'summer 2014',
'link'=>'link4'
),
array(
'season'=>'winter 2013',
'link'=>'link5'
)
);
所以现在我想让它像下面这样:
$dataArray =array(
'2014'=>array(
'winter'=>'link1',
'summer'=>'link4'
),
'2013' =>array(
'summer'=>'link2',
'winter'=>'link5'
),
'2012'=>array(
'fall'=>' link3',
'link'=>'link3'
),
);
我只是想用下面的代码找到解决问题的方法,但到目前为止还没有运气:(
$newArray =array();
$innerArray=array();
foreach ($infoArray as $info){
$season = explode(" ", $info['season']);
$seasonName = $season[0];
$seasonYear = $season[1];
if (array_key_exists($seasonYear, $newArray)) {
$newArray[$seasonYear][$seasonName]=$info['link'] ;
}
else {
$innerArray[$seasonName] = $info['link'];
$newArray[$seasonYear]=$innerArray ;
}
}
我希望有人可以指出我哪里出错或者是更好的解决方案。
提前致谢。
答案 0 :(得分:0)
你使它变得比它需要的更复杂。
$infoArray =array(
array(
'season'=>'winter 2014',
'link'=>'link1'
),
array(
'season'=>'summer 2013',
'link'=>'link2'
),
array(
'season'=>'fall 2012',
'link'=>'link3'
),
array(
'season'=>'summer 2014',
'link'=>'link4'
),
array(
'season'=>'winter 2013',
'link'=>'link5'
)
);
foreach ($infoArray as $element) {
list($season, $year) = explode(' ', $element['season']);
$dataArray[$year][$season] = $element['link'];
}
var_export($dataArray);
array (
2014 =>
array (
'winter' => 'link1',
'summer' => 'link4',
),
2013 =>
array (
'summer' => 'link2',
'winter' => 'link5',
),
2012 =>
array (
'fall' => 'link3',
),
)