似乎无法将数组转换为JSON PHP

时间:2016-11-26 11:55:44

标签: php arrays json

因此我正在使用php和javascript在这个图表谷歌可视化,但我似乎无法让json转换工作。

这是我的php代码:


"uglify-js": "git://github.com/mishoo/UglifyJS2#harmony-v2.8.22",

我在这里看了一下SO,但人们说工作的转换似乎无法开始工作。我试过了:

$sql = "select pNavn, antallTimer from Prosjekter where userId=".$userId;
$result = hentData($sql);
$orders = array(array('Prosjekt navn', 'Antall Timer'));
/* Extract the information from $result */
while ( $rad = mysqli_fetch_assoc($result) ) {
    $temp = array($rad['pNavn'], $rad['antallTimer']);
    array_push($orders, $temp);
}
$orders=json_encode($orders);
var_dump($orders);

json_encode(
    iconv(
        mb_detect_encoding($orders, mb_detect_order(), true),
        'UTF-8',
        $orders
    )
)

第一个给出了mb_convert_variables('utf-8', 'original encode', array/object) 数组而不是字符串的错误原因,第二个没有给出任何错误,但$orders的{​​{1}}仍然是错误的。

var_dumps im getting:

var_dump

我需要帮助的是使JSON与此piechart一起使用 请帮助,绝望在这里:)

2 个答案:

答案 0 :(得分:1)

我想出来并让它发挥作用。感谢您帮助我尝试引导我走上严峻的道路。结果证明是utf-8编码的问题。工作代码如下:

$sql = "select pNavn, antallTimer from Prosjekter where userId=".$userId;
    $result = hentData($sql);
$table = array();
$table['cols'] = array(
array('label' => 'Prosjekt Navn', 'type' => 'string'),
array('label' => 'Timer', 'type' => 'number')
);

$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$temp = array();
$temp[] = array('v' => iconv(mb_detect_encoding($r['pNavn'], mb_detect_order(), true), "UTF-8", $r['pNavn']));
$temp[] = array('v' => (int) $r['antallTimer']);
$rows[] = array('c' => $temp);
}

$table['rows'] = $rows;

$jsonTable = json_encode($table);

答案 1 :(得分:0)

从你的问题不清楚你想要输出是什么,但似乎你想要将你的值从mysql fetch添加到你创建的数组作为$ orders的子数组。所以也许你打算做这样的事情:

$columns = array(
    array('label' => 'Prosjekt navn', 'type' => 'string'),
    array('label' => 'Antall Timer', 'type' => 'number')
);
$orders = array($columns);
/* Extract the information from $result */
while ( $rad = mysqli_fetch_assoc($result) ) {
    $row = array($rad['pNavn'], $rad['antallTimer']);
    array_push($orders, $row);
}
$orders=json_encode($orders);
var_dump($orders);

更新: 根据您对Google可视化API的使用情况,您的JSON数据看起来不正确,无法提供给arrayToDataTable方法。文档声明您的数据需要按照示例进行格式化:

var data2 = google.visualization.arrayToDataTable([
    [{label: 'Country', type: 'string'},
    {label: 'Population', type: 'number'},
    {label: 'Area', type: 'number'},
    {type: 'string', role: 'annotation'}],
    ['CN', 1324, 9640821, 'Annotated'],
    ['IN', 1133, 3287263, 'Annotated'],
    ['US', 304, 9629091, 'Annotated'],
    ['ID', 232, 1904569, 'Annotated'],
    ['BR', 187, 8514877, 'Annotated']
]);

根据该格式,您的第一行应包含标签和类型表示法,其余行应该是您的数据。我已更新上面的代码以反映此格式。这是未经测试的,但应该接近Googl可视化API所需的内容。