I am trying to create multidimensional array from MySQL query
Query:
$STH = $DBH->query( "SELECT value, o_ID, oName, date,
DATE_FORMAT(date, '%d %m %Y') as FDate,
DATE_FORMAT(tsTime, '%H:%i') as FTime
FROM test tst
LEFT JOIN object o
ON tst.o_ID =o.oID
WHERE DATE(date) = '$date'
ORDER BY FDate, FTime, oName ASC");
$STH->setFetchMode(PDO::FETCH_ASSOC);
Loop:
$returnValue = array();
$data = array();
while ( $row = $STH->fetch() ) {
$returnValue[$row['oName']] =
array(
$data[] = array(
'time' => $row['FTime'], 'value' => $row['value']
)
);
}
Output:
{"objectA":[{"time":"23:55","value":"15"}],"objectB":[{"time":"23:55","value":"15.90"}],..}
how can I put all values in $data array?
Desired output:
{"objectA":[{"time":"01:00","value":"15"},{"time":"02:00","value":"11"},{"time":"03:00,"value":"16"}],"objectB":[{"time":""01:00","value":"12"},{"time":""02:00","value":"25"},{"time":""03:00","value":"5"}],..}
Give this a shot:
$returnValue = array();
while ( $row = $STH->fetch() )
{
if (!$returnValue[$row['oName']])
{
$returnValue[$row['oName']] = array();
}
$returnValue[$row['oName']][]= array(
'time' => $row['FTime'], 'value' => $row['value']
);
}
That should give you what you want.
The difference here is that, if the oName-key doesn't exits, I create it, and assign it a new, empty array, then I add a new assiciative array to that array.
When the oName of row N already has a matching key, I'm not going to reassign that key, but I'm just going to push an extra array to that key.
Try this:
while ( $row = $STH->fetch() ) {
$returnValue[] = array(
'time' => $row['FTime'], 'value' => $row['value']
);
}
Related
I have a table on the frontend, where the user can choose what types of columns he wants.
After submitting the form I get the array with selected columns.
For instance the user select following columns:
$columns = ["campaign_start_time", "campiagn_end_time", "campaign_id", "campaign_budget", "adset_name", "ad_name"]
Now I have to make the request to the facebook api, but facebook api only request query in form:
$query = "campaign{start_time, end_time, id, budget}, adset{name}, ad{name}"
Here is my question, what is the best way to convert $columns to $query in PHP language?
If you can construct your submitted data to be in this form:
Array
(
[campaign] => Array
(
[0] => start_time
[1] => end_time
[2] => id
[3] => budget
)
[adset] => Array
(
[0] => name
)
[ad] => Array
(
[0] => name
)
)
Maybe using inputs or other constructs such as:
name="campaign[]" value="start_time"
name="campaign[]" value="end_time"
Then looping and building the query with the keys and values will do it:
foreach($columns as $key => $val) {
$query[] = $key . '{' . implode(',', $val) . '}';
}
$query = implode(',', $query);
Otherwise you'll need to parse it to get what you need first, then execute the loop above using $result instead:
foreach($columns as $val) {
preg_match('/^([^_]+)_(.*)/', $val, $match);
$result[$match[1]][] = $match[2];
}
This solution splits apart the values based on underscores and then joins them back together as nested values based on the category/key. Note that this doesn't check for items that don't have a "prefix".
<?php
$columns = ["campaign_start_time", "campaign_end_time", "campaign_id", "campaign_budget", "adset_name", "ad_name"];
$criteria = [];
foreach( $columns as $column ){
$pieces = explode('_',$column);
$category = array_shift($pieces);
if( !isset($criteria[$category]) ){
$criteria[$category] = [];
}
$criteria[$category][] = implode('_', $pieces);
}
$queryPieces = [];
foreach($criteria as $category => $values){
$queryPieces[] = $category.'{'.implode(', ', $values).'}';
}
$query = implode(', ', $queryPieces);
This question already has answers here:
Create flat array of individual values from rows of comma-separated values fetched from a database table
(5 answers)
Closed 6 months ago.
I know that there are a lot of similar threads on Stack Overflow, but none of them works in my case.
My goal is to get the unique show genres from the database. They are stored (1,2,3 or more) comma separated in the show_genres column.
$link = mysqli_connect('127.0.0.1', 'root', 'pw', 'db');
$query = "SELECT show_genres FROM tv_shows";
$result = mysqli_query($link, $query);
foreach ($result as $value) {
$sh_genres = $value['show_genres'];
$sh_genres_array = array_map('trim', explode(',',$sh_genres));
// $doesnt_work = call_user_func_array("array_merge",
$sh_genres_array); // doesn't work for me
echo '<pre>' . var_export($sh_genres_array, true) . '</pre>';
}
My result is as follows:
array (
0 => 'Drama',
1 => 'Action',
2 => 'Crime',
)
array (
0 => 'Drama',
1 => 'Crime',
)
array (
0 => 'Drama',
1 => 'Thriller',
)
array (
0 => 'DIY',
)
array (
0 => 'Drama',
1 => 'Mystery',
2 => 'Supernatural',
)
However, I need just one array which contains the unique values, such as:
array (
0 => 'Drama',
1 => 'Mystery',
2 => 'Supernatural',
4 => 'Thriller',
5 => 'DIY',
6 => 'Crime',
7 => 'etc...'
)
If I try to create some array before the foreach loop and then store the data into it, such approach doesn't give a result as well.
Perhaps, there is a more simple solution by the means of SQL!?!?
Please try this code
In SQL
$query = "SELECT show_genres FROM tv_shows GROUP BY show_genres";
In PHP
$newArray = array();
foreach ($result as $value) {
$sh_genres = $value['show_genres'];
$sh_genres_array = array_map('trim', explode(',',$sh_genres));
$newArray = array_merge($newArray , $sh_genres_array );
}
$newUniqueArray = array_unique($newArray);
try using this code
$link = mysqli_connect('127.0.0.1', 'root', 'pw', 'db');
$query = "SELECT show_genres FROM tv_shows";
$result = mysqli_query($link, $query);
$sh_genres_array = [];
foreach ($result as $value) {
$sh_genres = $value['show_genres'];
$sh_genres_array = array_merge(
$sh_genres_array ,
array_map('trim', explode(',',$sh_genres))
);
}
echo '<pre>' . var_export(array_unique($sh_genres_array), true) . '</pre>';
Update
Please consider normalizing your database
Not sure but try this.
$genre_arr = RecursiveIteratorIterator(new RecursiveArrayIterator($sh_genres_array));
$unique_genre = array_unique($genre_arr);
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
}
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.
$feeds = array();
$query = "SELECT * FROM actions WHERE user_id = '$user_id'";
$result = mysql_query($query);
while ($info = mysql_fetch_array($result)) {
$feeds[][$info['date']] = array("feed" => array($info['ID'] => $user_id));
}
$query = "SELECT * FROM follows WHERE user_id = '$id'";
$result = mysql_query($query);
while ($info = mysql_fetch_array($result)) {
$feeds[][$info['date']] = array("follow" => $info['user_id']);
}
I would like to sort that $feeds array in date format (Y-m-d H:i:s) using [$info['date']] key
How can i do that ?
thanks
EDIT:
example of what i want to see as result is
$feeds = array(
0 => array(
'<date>' => array("feed" => array("feed_id" => "user_id"));
),
1 => array(
'<date>' => array("follow" => "user_id" );
),
);
I want to group/sort them in DATE key and do sth depends on if it is FEED or FOLLOW
The best way is to do it in database (faster)!
But if you want do it in PHP, your need uksort (for sorting) + foreach (for grouping) I think