我不熟悉PHP关联数组,所以我希望有人可以对这个问题有所了解并建议如何解决我的特定问题。
我有一个数据数组,其中每个元素都是一个“Month, Year
”字符串。
我想解析这些数据并创建一个关联数组,其中键是年份,值是那一年的数月数组。
例如,我有array("November, 2011", "May, 2011", "July, 2010")
使用foreach循环,我想解析这些数据并创建数组:
array( "2011" => array("Novemeber", "May"), "2010" => array("July"))
从我所看到的,我需要知道如何检查密钥是否存在,如果它不是创建它并将新数组作为其值,如果是,则将月份附加到已存在的值阵列。
如果这是有道理的,任何帮助将不胜感激!谢谢!
答案 0 :(得分:5)
$arr = array("November, 2011", "May, 2011", "July, 2010");
// An array to hold the output
$outarr = array();
foreach ($arr as $pair) {
// Split the month/year from each pair
list($mon, $year) = explode(",", $pair);
// Trim whitespace on the $year
$year = trim($year);
// If the year key isn't set, create it now
if (!isset($outarr[$year])) $outarr[$year] = array();
// And append the month. Don't forget to trim whitespace!
$outarr[$year][] = trim($mon);
}
输出:
print_r($outarr);
Array
(
[ 2011] => Array
(
[0] => November
[1] => May
)
[ 2010] => Array
(
[0] => July
)
)
答案 1 :(得分:2)
<?php
$initialArray = array("November, 2011", "May, 2011", "July, 2010");
$finalArray = array();
foreach($initialArray as $value)
{
// Note: I suppose here that each initialArray element is "<Month>, <Year>",
// otherwise the following line may trigger errors.
list($month, $year) = array_map('trim', explode(",", $value));
if (!isset($finalArray[$year]))
$finalArray[$year] = array();
$finalArray[$year][] = $month;
}
// orders years, however months arrays below years won't be ordered.
ksort($finalArray);
答案 2 :(得分:1)
试试这个(编辑第二遍,忘记关键字array
,添加修剪):
$array = array("November, 2011", "May, 2011", "July, 2010");
foreach ($array as $element) {
list($month, $year) = explode(',', $element);
$years[trim($year)][] = trim($month);
}
答案 3 :(得分:1)
好的,让我们试试这个:
<?php
$my_array = array('November, 2011', 'May, 2011', 'July, 2010');
$final = array();
foreach($my_array as $item) {
// Let's split the Month and Year
$item = explode(', ', $item);
$final[$item[1]][] = $item[0];
}
print_r($final);
?>
最终输出应为:
Array
(
[2011] => Array
(
[0] => November
[1] => May
)
[2010] => Array
(
[0] => July
)
)