-3

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.

amphetamachine
  • 27,620
  • 12
  • 60
  • 72
NikolaN
  • 3
  • 4
  • Where would the [years I'm assuming] come from? Are they in your array? What does View Source say is being output? – amphetamachine Dec 02 '22 at 18:52
  • 1
    The better way to get php data from server is making an AJAX request. – Pascal Tovohery Dec 02 '22 at 18:52
  • @amphetamachine years are from mysql database and they are loaded right into var oData without error. – NikolaN Dec 02 '22 at 18:53
  • 2
    Put the actual output. Not `"asd" or "ddd"` – itachi Dec 02 '22 at 18:56
  • @SebastianSimon I updated the php part in which I am getting the table. – NikolaN Dec 02 '22 at 18:56
  • 2
    *"Output is: ... Example output"*: I don't see any connection between the two. Can you explain how to get the second from the first? – trincot Dec 02 '22 at 18:57
  • @itachi its the actual otput. I just need that output to be formated to the Example output so it goes "asd:2" like this "asd": 2 – NikolaN Dec 02 '22 at 18:58
  • `$dataGrafDodArt[] = $row["art_naz"]. ":". $row["art_nabcena"];` adds a string to a regular array. You probably mean `$dataGrafDodArt[$row["art_naz"]] = $row["art_nabcena"];`. Just read the [documentation](//www.php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying). – Sebastian Simon Dec 02 '22 at 19:00
  • 3
    Can you edit your question and make the two outputs consistent with eachother? – trincot Dec 02 '22 at 19:01

1 Answers1

1

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"];
trincot
  • 317,000
  • 35
  • 244
  • 286