php关联数组 - 添加键/值,检查键存在,向值数组添加值

And*_*rew 3 php arrays

我不熟悉PHP关联数组,所以我希望有人可以对这个问题有所了解并建议如何解决我的特定问题.

我有一个数据数组,其中每个元素都是一个字符串" Month, Year".我想解析这些数据并创建一个关联数组,其中键是年份,值是该年的月份数组.

例如,我有array("November, 2011", "May, 2011", "July, 2010") 使用foreach循环,我想解析这些数据并创建数组:

array( "2011" => array("Novemeber", "May"), "2010" => array("July"))
Run Code Online (Sandbox Code Playgroud)

从我所看到的,我需要知道如何检查密钥是否存在,如果它不是创建它并将新数组作为其值,如果是,则将月份附加到已存在的值数组.

如果这是有道理的,任何帮助将不胜感激!谢谢!

Mic*_*ski 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);
}
Run Code Online (Sandbox Code Playgroud)

输出:

print_r($outarr);
Array
(
    [ 2011] => Array
        (
            [0] => November
            [1] => May
        )

    [ 2010] => Array
        (
            [0] => July
        )  
)
Run Code Online (Sandbox Code Playgroud)