如何json_encode php数组但没有引号的键 [英] How to json_encode php array but the keys without quotes
问题描述
我正在尝试绘制(使用Flot)带有一些数据的饼图
I'm trying to plot (with Flot) a pie chart with some data
var data = <?php echo json_encode($data)?>
我从中得到的结果是:
var data = [
{"label":"Crear Usuario", "data":"2"},
{"label":"Impresoras", "data":"1"},
{"label":"Problema Correo", "data":"1"},
{"label":"Requisicion Equipo", "data":"1"},
{"label":"Sitio Web", "data":"1"}
]
这里的问题是我需要没有引号的 label
和 data
,我已经尝试过 json_encode($data, JSON_NUMERIC_CHECK);
但只从数字中删除引号.
The problem here is that I need the label
and data
without the quotes, I already tried json_encode($data, JSON_NUMERIC_CHECK);
but only removes the quotes from the numbers.
以下格式是我需要的:
var data = [
{label:"Crear Usuario",data:2}, ...
推荐答案
首先,您必须在 php 中生成数组,以便数据的值是整数,而不是字符串:
First, you have to generate your array in php so the data's value are integers, not strings:
我从你的 json_encode() 模拟了你的数组,我猜它看起来像这样(或者应该):
I emulated your array from your json_encode(), I guess it looks like this (or it should):
$array = array(
array("label" => "Crear Usuario", "data" => 2),
array("label" => "Impresoras", "data" => 1),
array("label" => "Problema Correo", "data" => 1),
array("label" => "Requisicion Equipo", "data" => 1),
array("label" => "Sitio Web", "data" => 1)
);
$data = json_encode($array);
- 请注意,2 和 1 没有加引号,因此它们是整数,这一点很重要.
然后您在 Javascript 中缺少 JSON.parse() 来实际将该输出转换为 json 对象:
Then you are missin in Javascript the JSON.parse() to actually make that output into a json object:
<script>
var data = '<?php echo $data; ?>';
var json = JSON.parse(data);
console.log(json);
console.log(json[0]);
</script>
- 请注意 var data = ... 是单引号,因此您可以将来自 php 的回显作为字符串捕获
console.log() 为我输出这个:
The console.log()'s output this for me:
[Object, Object, Object, Object, Object] // First console.log(): one object with the 5 Objects.
Object {label: "Crear Usuario", data: 2} // secons console log (json[0]) with the first object
看起来像你需要的,对吗?
Looks like what you need, am I right?
这篇关于如何json_encode php数组但没有引号的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!