javascriptphparraysjsonarrayobject

How to convert JSON array to OBJECT array javascript?


Kinda stuck here.

I am fetching data from database with php into this variable in javascript.

<?php
//connection to database
include("con.php");
//query
$query = "SELECT * FROM magacin_artikli";

$r = mysqli_query($conn, $query);

$dataGrafDodArt = array();

while($row = mysqli_fetch_array($r)){
  $dataGrafDodArt[] = $row["art_naz"]. ":". $row["art_nabcena"];

}

//closing conn
$conn->close();

?>
var oData = <?php echo json_encode($dataGrafDodArt);?>;

Output is:

var oData = ["asd:2","asd:3","asd:2","ddd:3"];

And I need this to be formated like object array like this("asd":2), something like this inside variable:

Example output:

var oData = {
  "2008": 10,
  "2009": 39.9,
  "2010": 17,
  "2011": 30.0,
  "2012": 5.3,
  "2013": 38.4,
  "2014": 15.7,
  "2015": 9.0
};

This is for animated graph which is taking parameters from Example output.

Any help would be good.

Tried a lot of things from array map to trimming the array and other stuff but none worked.


Solution

  • You should make the change at the PHP side. Instead of building an indexed array, create an associative array, and it will look in JavaScript just as you wanted it.

    Change this:

    $dataGrafDodArt[] = $row["art_naz"]. ":". $row["art_nabcena"];
    

    To:

    $dataGrafDodArt[$row["art_naz"]] = $row["art_nabcena"];