如何将数组值推入json字符串

时间:2017-10-03 04:30:40

标签: php mysql arrays json

我有这个json字符串作为绘制图表的数据表:

{"cols":[
     {"id":"","label":"Month","pattern":"","type":"string"}, 
     {"id":"","label":"Job","pattern":"","type":"number"},
     {"id":"","label":"Internship","pattern":"","type":"number"}],
"rows":[
     {"c":[{"v":"July","f":null},{"v":6,"f":null},{"v":2,"f":null}]},
     {"c":[{"v":"August","f":null},{"v":0,"f":null},{"v":3,"f":null}]}]}

json字符串派生自此数组(值来自sql查询):

$rows = array_map(function($item) {
return (object) ['c' => [
    (object) ['v' => $item->month, 'f' => null],
    (object) ['v' => intval($item->jobcount), 'f' => null],
    (object) ['v' => intval($item->interncount), 'f' => null]
]];
}, array_values($data));


// prepare return data
$cols = [
(object) ['id' => '', 'label' => 'Month', 'pattern' => '', 'type' => 'string'],
(object) ['id' => '', 'label' => 'Job', 'pattern' => '', 'type' => 'number'],
(object) ['id' => '', 'label' => 'Internship', 'pattern' => '', 'type' => 'number'],
];

$returndata = new stdClass;
$returndata->cols = $cols;
$returndata->rows = $rows;

echo json_encode($returndata);

我想在1月到12月之间插入另外几个月,将jobcount和interncount的0值插入到json字符串中。

如何将此数组放入json字符串中,以便将其他月份包含在图表中?

$months = array('January', 'February', 'March', 'April', 'May', 'Jun', 'July', 'August', 'September', 'October', 'November', 'December');

这是图表。

chart

1 个答案:

答案 0 :(得分:0)

如果您在执行所有转换以生成最终对象之前将空白月份添加到源数据中,我认为会更容易。看看你的代码,我看起来像array_values($data)就是这个......

[
    { month: 'July', jobcount: "6", interncount: "2" },
    { month: 'August', jobcount: "0", interncount: "3" }
]

这个想法是遍历所有月份,并在每次交互检查中是否存在月份,如果不存在,则添加一个空行。但为了避免在一个对象数组中搜索一个月的存在,我将首先在数组中提取当前月份列表...

// Your source data.
$currentdata = array_values($data);

// Lets's extract all months from your data into an array.
$datamonths = array();
foreach ($currentdata as $monthdata)
    $datamonths[] = $monthdata->month;

// Now, let's loop all months and check if are present or not in our data.
$allmonths = array('January', 'February', 'March', 'April', 'May', 'Jun', 'July', 'August', 'September', 'October', 'November', 'December');

$newsourcedata = array();
foreach ($allmonths as $onemonth) {
    if (($pos=array_search($onemonth,$datamonths)) === false)
        $newsourcedata[] = (object) ['month'=>$onemonth,'jobcount'=>"0",'interncount'=>"0"];
    else
        $newsourcedata[] = $currentdata[$pos];
}

// Now goes the rest of your code, but changing the sourcedata for the new one...
$rows = array_map(function($item) {
    return (object) ['c' => [
        (object) ['v' => $item->month, 'f' => null],
        (object) ['v' => intval($item->jobcount), 'f' => null],
        (object) ['v' => intval($item->interncount), 'f' => null]
    ]];
},$newsourcedata);

..........

我希望它有所帮助。