我从一行获取数据是一堆整数,我需要用逗号分隔它们以将它们用于chart.js数据集数据。所以我在这里有阵列:
if (mysqli_num_rows($result) > 0) {
$categories = [];
while($row = mysqli_fetch_assoc($result)) {
$categories[] = $row;
}
echo json_encode($categories);
我需要把它变成json编码的字符串:
我的阵列回声为:
[{"respondent_sdo":"2","respondent_dcto":"3","respondent_ed":"5","respondent_ca":"5","respondent_dhpt":"3","respondent_irt":"6","respondent_gl":"2","respondent_il":"5"}]
我需要将上面的内容输出为2,3,5,5,3,6,5
var dataString= "<?php echo json_encode($categories, JSON_NUMERIC_CHECK); ?>";
var catData = JSON.parse(dataString);
var ctx = document.getElementById("myChart1");
var myChart1 = new Chart(ctx, {
type: 'radar',
options: {
legend: {
display: true
},
tooltips: {
enabled: false
},
scale: {
ticks: {
beginAtZero: true,
stepSize: 1
}
}
},
data: {
labels: ["Strategic Development and Ownership",
"Driving change through others",
"Exec Acumen",
"Commercial Acumen",
"Develops High Performance Teams",
"Innovation and risk taking",
"Global Leadership",
"Industry Leader"
],
datasets: [{
label: 'Ian Galbraith',
backgroundColor: "rgba(255,6255,255,0)",
borderColor: "lightblue",
data: catData,
}]
}
});
答案 0 :(得分:2)
为什么不在PHP文件中将关联数组更改为数字数组,如:
而不是:
if (mysqli_num_rows($result) > 0) {
$categories = [];
while($row = mysqli_fetch_assoc($result)) {
$categories[] = $row;
}
echo json_encode($categories);
使用:
if (mysqli_num_rows($result) > 0) {
$categories = [];
while($row = mysqli_fetch_assoc($result)) {
$categories[] = $row;
}
$response = array();
foreach($categories as $c){
foreach($c as $val){
$response[] = (int)$val;
}
}
echo json_encode($response);
我希望它有所帮助
答案 1 :(得分:1)
要实现此目的,您可以使用Object.keys
从对象获取密钥,然后使用这些密钥中的值填充数组:
// Use this in production
//var arr = <?php echo json_encode($categories, JSON_NUMERIC_CHECK); ?>;
// For this example:
var arr = [{
"respondent_sdo": "2",
"respondent_dcto": "3",
"respondent_ed": "5",
"respondent_ca": "5",
"respondent_dhpt": "3",
"respondent_irt": "6",
"respondent_gl": "2",
"respondent_il": "5"
}]
var catData = [];
Object.keys(arr[0]).forEach(function(key) {
catData.push(parseInt(arr[0][key], 10));
});
console.log(catData);
&#13;
但是,我建议您改为执行逻辑来提取PHP代码中的整数,并将它们提供给JS。
答案 2 :(得分:1)
或者使用数组映射函数。
var catData = JSON.parse(dataString);
var values ='';
values += catData.map(function(a) {
return a.foo+',';
});
values = values.replace(/,\s*$/, ""); //to remove last coma