Michał Lipa
Michał Lipa

Reputation: 117

Formatting output from an array

I would like to create graph by PHPGraphlib using my data from database.

My problem is, that I have array in different format and PHPGraphlib doesn't read it.

PHPGraphlib reads array like this:

$data = array("15:01:14" => .0032, "15:05:14" => .0028, "15:10:14" => .0021, "15:15:14" => .0033, 
"15:20:14" => .0034);

and I create my array:

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$orders[] = array(
'price' => $row['price'],
'clock' => $row['clock'],
);
}

echo json_encode($orders);

so it looks like this:

[{"price":"1570","clock":"14:56:02"},{"price":"1570","clock":"15:01:14"},{"price":"1571","clock":"15:11:49"}]

How can I get this same output like first one, to get PHPGraphlib read my array.

Upvotes: 0

Views: 137

Answers (2)

ThatMSG
ThatMSG

Reputation: 1506

Well it does this becaus you are using json_encode($orders).

This will convert

array("15:01:14" => .0032, "15:05:14" => .0028, ...

in

[{"15:01:14":".0032"},{"15:05:14":".0028"} , ...

since you are converting a php array to a json object. The example from Adil will create an array exactly like your $data array :) Btw if you want to implement some more security take a look at this : http://php.net/manual/de/mysqli.prepare.php it will prevent such ugly things like SQL-Injections ;)

Just in case you are looking for something like this:

$tmp = '';
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $tmp .= '"'.$row['clock'].'" => "'.$row['price'].'",';
}

echo $tmp;

This will output: String "15:01:14" => ".0032", "15:05:14" => ".0028",...

Upvotes: 0

Adil Abbasi
Adil Abbasi

Reputation: 3291

Try like this,

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $orders[$row['clock']] = $row['price'];
}

imp: avoid using mysql use mysqli or pdo

Upvotes: 1

Related Questions