Dan Dan - 10 days ago 9
Javascript Question

Turn a php array into comma separated array

I am getting data from a row which are a bunch of integers and I need to comma separate them to use them for a chart.js dataset data. So I have got the array here:

if (mysqli_num_rows($result) > 0) {

$categories = [];
while($row = mysqli_fetch_assoc($result)) {
$categories[] = $row;
}

echo json_encode($categories);


I need to turn it into json encoded string:

My array echos out as:

[{"respondent_sdo":"2","respondent_dcto":"3","respondent_ed":"5","respondent_ca":"5","respondent_dhpt":"3","respondent_irt":"6","respondent_gl":"2","respondent_il":"5"}]


To which I need the above to output as
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,
}]
}
});

Answer

Why don't you change associative array into numeric one in PHP file like:

Instead of:

if (mysqli_num_rows($result) > 0) {

  $categories = [];
  while($row = mysqli_fetch_assoc($result)) {
    $categories[] = $row;     
  }

echo json_encode($categories);

Use:

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);

I hope it helps

Comments