用PHP创建一个带有数组数组的json对象


Create a json object with array of arrays in PHP

我正在使用array_add($array, 'key', 'value');来创建数据结构。

foreach ($archives as $archive){
    $results = array_add($results, $archive->year, 
              array($archive->month => array('name' => $archive->month_name)));
}

如果i json_encode(),则$results i得到此输出:

{ 
   2015: {
       02: {name:'February'}
   }
}

但我想要一些类似的东西:

{
   2015: {
       02: {name:'February'},
       01: {name:'January'}
   }
}

当然,这也适用于不同的年份。

为了回应我的评论,我会这样做:

foreach ($archives as $archive)
{
    if (!isset($results[$archive->year]))
    {//if the year-key doesn't exist yet, create it
     //if it already exists, this part will be skipped
        $results[$archive->year] = array();
    }
    //then add the values
    $results[$archive->year][$archive->month] = array(
        'name' => $archive->month_name
    );
}

这就是它的全部,不需要自制函数或类似的任何东西

怎么样array_push($array,'key','value');