Create Array from Mysql data for Flot - php

I have a problem in that I can't get an array into an array.
The outcome should look like this:
$data=array(
array(
'label' => 'Totals',
'color' => '#745fa4',
'data' =>
array(
array('01/01/2015', 125),
array('02/01/2015', 148),
array('03/01/2015', 42),
array('04/01/2015', 115),
array('05/01/2015', 45),
array('06/01/2015', 77),
array('07/01/2015', 59)
)
),
);
I currently have this but can't get it into the correct format:
$result = mysqli_query($con,"SELECT * FROM table ORDER BY id DESC LIMIT 28");
$chartdata = array();
while($row = $result->fetch_assoc()) {
$chartdata[] .= array($row["date"]. ", " . $row["total"]);
}
$data=array(
array(
'label' => 'Totals',
'color' => '#745fa4',
'data' => $chartdata
)
);
If someone could help me out that would be fantastic.

1) .= this means assignment with string concatenation. you should push array into parent array
2) inside child array have two values not single string so use , between two value not string concatenation ","
$chartdata[] .= array($row["date"]. ", " . $row["total"]);
to
$chartdata[] = array($row["date"], $row["total"]);

You have a superfluous dot here:
# ⇓
$chartdata[] .= array($row["date"]. ", " . $row["total"]);
To push new item into an array one should use $array[] = $item:
$chartdata[] = array($row["date"]. ", " . $row["total"]);
Dot is used to concatenate strings. Hope it helps.

Remove the dot.
<?php
$result = mysqli_query($con,"SELECT * FROM table ORDER BY id DESC LIMIT 28");
$chartdata = array();
while($row = $result->fetch_assoc()) {
$chartdata[] = array($row["date"], $row["total"]); // Remove the dot
}
$data=array(
array(
'label' => 'Totals',
'color' => '#745fa4',
'data' => $chartdata
)
);

Related

Problems with mysqli_fetch_array

I want to put the result of my request in this array, $dataPoints1 = array, but it doesn't work.
This is my request:
$sql = "
SELECT COUNT(id_etudiant)as nbre1 FROM suivre WHERE n_formation='1'
UNION
SELECT COUNT(id_etudiant)FROM suivre WHERE n_formation='2'
UNION
SELECT COUNT(id_etudiant)FROM suivre
WHERE n_formation='3'";
$result = mysqli_query($link,$sql);
while($row = mysqli_fetch_array($result)) {
$dataPoints1 = array(
array("y" => ''. $row["nbre1"].'',"label" => "formation1" ),
array("y" => ''. $row["nbre1"].'',"label" => "formation2" ),
array("y" => ''. $row["nbre1"].'',"label" => "formation3" ),
);}
You can start by simplifying your sql
SELECT COUNT(id_etudiant)as nbre1, n_formation as formation FROM suivre GROUP BY n_formation;
Start by declaring your array outside of your loop then add to the next index by using the "[]".
Try this:
$dataPoints1 = array();
while($row = mysqli_fetch_array($result)) {
$dataPoints1[] = array("y" => $row["nbre1"], "label" => $row['formation'] )
or
$dataPoints1[] = $row
}

Convert PHP Array to JSON Array of object

I'm using Google Orgchart in my project. In that I'm returning JSON OBJECT from PHP file.
Problem
My Problem is when I hardcode the value, It works fine. When I return data from PHP file. It did not work. I guess the data format which is returning from PHP file is not correct. File below.
$result = mysql_query("SELECT * FROM emp");
while($row = mysql_fetch_array( $result )) {
$arr1 = array(
'v' => $row['name'],
'f' => $row['name']+'<div style="color:red; font-style:italic">President</div>',
'' => $row['rep'],
'' => $row['des'],
);
array_push($dataarray, $arr1);
}
echo json_encode($dataarray);
which returns object like below
How it Should be
My hardcorded JSON OBJECT below
[
[{v:'Prabhkar', f:'Prabhkar<div style="color:red; font-style:italic">President</div>'},
'', 'The President'],
[{v:'Raguram', f:'Raguram<div style="color:red; font-style:italic">GM</div>'},
'Prabhkar', 'GM']
]
Console Screenshot below:
Do I need to create a one more array in PHP file. How I suppose to change the PHP array according to above screenshot. sorry for my english. Thank you.
You need to wrap 'v' and 'f' in a array, then push other values to parent array.
$result = mysql_query("SELECT * FROM emp");
while($row = mysql_fetch_array( $result )) {
$arr1 = array(
array(
'v' => $row['name'],
'f' => $row['name'] . '<div style="color:red; font-style:italic">President</div>'
),
$row['rep'],
$row['des']
);
array_push($dataarray, $arr1);
}
echo json_encode($dataarray);
In your hard coded array the first key has an array inside so you must change your code like this
$result = mysql_query("SELECT * FROM emp");
$dataarray = [];
while($row = mysql_fetch_array( $result )) {
$arr1 = array(
array(
'v'=> $row['name'],
'f' => $row['name'].'<div style="color:red; font-style:italic">President</div>',),
$row['rep'],
$row['des'],
);
array_push($dataarray, $arr1);
}
echo json_encode($dataarray);
Your internal structure is wrong. Your internal structure is an array, with the first being a map, followed by two values. Your current implementation is an array, with only a map.
$result = mysql_query("SELECT * FROM emp");
while($row = mysql_fetch_array( $result )) {
$arr1 = array(
array(
'v' => $row['name'],
'f' => $row['name'] . '<div style="color:red; font-style:italic">President</div>',
),
$row['rep'],
$row['des']);
array_push($dataarray, $arr1);
}
echo json_encode($dataarray);

Using an array value to retrieve from another array

I have created an array, one of the is intended to be a string used by php to display a field from a record retrieved from sqlite3.
My problem is that ... it doesn't.
The array is defined, "1" being the first database field, and "2" is the second database field:
EDIT : I have re-defined the problem as a script so you can see the whole thing:
//If I have an array (simulating a record retrieved from database):
$record = array(
name => 'Joe',
comments => 'Good Bloke',
);
//then I define an array to reference it:
$fields = array(
1 => array(
'db_index' => 'name',
'db_type' => 'TEXT',
'display' => '$record["name"]',
'form_label' => 'Name',
),
2 => array(
'db_index' => 'comments',
'db_type' => 'TEXT',
'display' => '$record["comments"]',
'form_label' => 'Comments',
),
);
//If I use the lines:
print "expected output:\n";
print " Name = " . $record["name"] ."\n";
print " Comments = " . $record["comments"] ."\n";
//I display the results from the $record array correctly.
//However if I try & use the fields array with something like:
Print "Output using Array values\n";
foreach($GLOBALS["fields"] as $field)
{
$label = $field['form_label'];
$it = $field['display'];
$line = "\"$label = \" . $it .\"\n\"";
print $line;
}
Output:
Expected output:
Name = Joe
Comments = Good Bloke
Output using Array values:
Name = $record["name"]
Comments = $record["comments"]
Don't call variable from string. Just concatenate it :
foreach($GLOBALS["fields"] as $field){
$label = $field['form_label'];
$it = $field['display'];
eval("$it = ".$it);
$line = $label." = ".$it."\n";
print $line;
}
Well, how do it looks ?

PHP array presentation

I have an php array with presentation as follow:-
<?php
$ads = array();
$ads [] = array(
'name' => 'Apple',
'duration' => '3',
'price' => "$5"
);
$ads [] = array(
'name' => 'Orange',
'duration' => '2',
'price' => "$10"
);
$ads [] = array(
'name' => 'Banana',
'duration' => '5',
'price' => "$6"
);
and then, I would like to replace the static data with dynamic data from database:-
$sql = "SELECT * from tb_fruit order by fruit_id ASC";
$result = mysql_query($sql_approve, $conn_fruit);
while($record = mysql_fetch_array($result))
{
$fruit_id = $record['fruit_id'];
$fruit_name = $record['fruit_name '];
$fruit_price= $record['fruit_price'];
$fruit_duration= $record_approve['fruit_duration'];
}
Actually, how shall I combine the 2 presentations together? Thanks!
If you want to get a similar structure as the one that you have in the first example, you can modify your second to create a new array and append it to an existing $ads array.
$sql = "SELECT * from tb_fruit order by fruit_id ASC";
$result = mysql_query($sql_approve, $conn_fruit);
$ads = array();
while($record = mysql_fetch_array($result))
{
$ads[] = array(
'name' => $record['fruit_name'],
'price' => $record['fruit_price'],
'duration' => $record['fruit_duration']);
}
iteration over result can be modified (provided only the required attributes are fetched in the query)
$fruit = array();
while($record = mysql_fetch_array($result))
{
$fruit[] = $record;
}
may be you could use array_merge
$result = array();
$result = array_merge($ads,$fruit);
So, you want to populate your "ads" array with information from the database? It seems fairly counterintuitive seeing as mysql_fetch_array already returns a perfectly adequate associative array, but here you go:
$sql = "SELECT * from tb_fruit order by fruit_id ASC";
$result = mysql_query($sql_approve, $conn_fruit);
$ads = array();
while($record = mysql_fetch_array($result))
{
$ads[] = array (
'name' => $record['fruit_name'],
'price' => $record['fruit_price'],
'duration' => $record['fruit_duration']
);
}
If
the initial array is not just an example, but default data that you might overwrite with the db data, and
the fruit name is unique (a primary key of sorts)
then you should set the array key of the main array to that of the fruit name, so that if the db has a different value, it will automatically get overwritten but otherwise left alone. Like so:
$ads ['Apple'] = array(
'duration' => '3',
'price' => "$5"
);
$ads ['Orange'] = array(
'duration' => '2',
'price' => "$10"
);
$ads ['Banana'] = array(
'duration' => '5',
'price' => "$6"
);
$sql = "SELECT * from tb_fruit order by fruit_id ASC";
$result = mysql_query($sql_approve, $conn_fruit);
$ads = array();
while($record = mysql_fetch_array($result))
{
$ads[$record['fruit_name']]['price'] = $record['fruit_price'];
$ads[$record['fruit_name']]['duration'] = $record['fruit_duration'];
}
Now, if 'Apple' is in the db, the price and duration get overwritten, but otherwise, it stays where you set it before the query.
You could go a step further and have both the price and duration returned by the query checked for an empty value (Null, "", 0), and only set the value if it is not empty, etc. But that is more a of business logic decision.

Ouput data in JSON format on Array in PHP

$result = mysql_query($query);
$leaderboard = array();
while($row = mysql_fetch_assoc($result)) {
$leaderboard[$row["username"]] = $row["score"];
}
$output = array
(
'status' => 1,
'content' =>$leaderboard
);
print_r(json_encode($output));
right now the $output array is such JSON:
{"tim":"120","john":"45","larry":"56"}
but I want to have them as key-value pair so instead I want to be like:
{"name":"tim","score":120","name":"john","score="45", etc.}
and if I need that way, how do I modify the $leaderboard array so the output would be like that?
$leaderboard[] = Array('name' => $row["username"], 'score' => $row["score"]);

Categories