json_encode的PHP数组格式

时间:2014-07-07 10:01:44

标签: php arrays

我正在用这个php查询创建一个数组..

PHP

$query = mssql_query("  SELECT count(startdate) as incept,  month(startdate) as month, year(startdate) as year
                        FROM tblUser
                        WHERE startdate >=  convert(varchar(20),'$val1',121) AND startdate <= convert(varchar(20),'$val2',121) 
                        GROUP BY  month(startdate), year(startdate) 
                        ORDER BY  year(startdate) ASC, month(startdate) ASC ");

while ($data = mssql_fetch_array($query)) {
    $name = $data['year'];
    $data = array($data['month'],$data['incept']);
    $case[$data['year']] = array('name' => $name, 'data' => $data);
}

我想将以上查询存储在以下结构中并将其传递给json。

$case = array(
'2011' => array(
    'name' => 2011,
    'data' => array(
        array('0', 166),
        array('1', 132),
        ..
        array('5', 160)
    )
),
'2012' => array(
    'name' => 2012,
    'data' => array(
        array('0', 142),
        ...
        array('5', 163)
    )
),
'2013' => array(
    'name' => 2013,
    'data' => array(
        array('0', 156),
        ...
        array('6', 198)
    )
)

有没有办法以这种格式生成?感谢

2 个答案:

答案 0 :(得分:1)

循环内部:

if (!isset($case[$data['year']])) {
    $case[$data['year']] = array(
        'name' => $data['year'],
        'data' => array()
    );
}

$case[$data['year']]['data'][] = array(
    $data['month'],
    $data['incept']
);

答案 1 :(得分:0)

你在你的第二行覆盖$ data数组,你可以这样做:

while ($data = mssql_fetch_array($query)) {
    $name = $data['year'];
    $data = array($data['month'],$data['incept']);
    if ( ! isset($case[$name]))
        $case[$name] = array('name' => $name, 'data' => $data);
    else
        $case[$name]['data'][] = $data;
}