Adding items to a multi-dimensional array during query while loop - php

I have a query returning data that looks like this:
Status Total
Success 234
Failed 20
Missing 12
I want to add this to an array which can then be used to populate a google pie chart.
the array would look like this:
array backup = array("Success" => 234),
("Failed" => 20),
("Missing" => 12);
How would I add these item dynamically at each row in a query?

$result = mysql_query(...);
$backup = array();
while ($r = mysql_fetch_assoc($result)) {
$backup[$r['Status']] = $r['Total'];
}
Here's how you can make the Google Charts API call:
$values = implode(',', array_values($backup));
$labels = implode('|', array_keys($backup));
$img = "http://chart.apis.google.com/chart?cht=p3&chd=t:{$values}&chl={$labels}&chs=250x100";
echo "<img src='{$img}' alt='Chart'>";

Assuming this is your query:
SELECT status, total FROM table
Then you can do:
$data = array();
while(($row = mysql_fetch_assoc($result))) {
$data[$row['status']] = $row['total'];
}
If this is not what you mean, please clarify your question and/or provide the code you already have.

I think we need a bunch more information, but in the mean time look at array_merge()
http://www.php.net/manual/en/function.array-merge.php

Related

PHP - Multidimensional Array

I am basically trying to fetch results from a SQL database and load that into a multidimensional array so i can use them later on in the page.
while($row = mysqli_fetch_array($result))
{
$send = array
(
array($row['Name'],$row['Email'],$row['Mobile'])
);
$count = $count + 1;
}
That is what i am using to get the results which if i print within the while loop it will echo all the results. However when putting it into the array it loads each result into the array as the first result. My initial plan was to use a counting variable to set where in the array the result was set to with this adding by one each time. I am not certain how to specify where to add the result i thought something along the lines of
$send = array[$count]
(
array.....
so i could then refer to the results as 0 to count length but i am not sure how to make this work. Or ,which i presume, if there is a much easier and better way of going about it. I am also not sure if this is necessary as surely the results seem to be in an array when gathered from the SQL database but i am unsure if this array is populated with each while loop or stored and can be accessed at any point
If any one can give me an example of something similar or point me at some documentation much appreciated
Try this:
$count = 0;
while ($row = mysqli_fetch_array($result)) {
$send[$count] = array($row['Name'], $row['Email'], $row['Mobile']);
$count++;
}
I have a better way for you. You could also use the id for your index, if you have one:
while ($row = mysqli_fetch_array($result)) {
$send[$row['id']] = array(
"Name" => $row['Name'],
"Email" => $row['Email'],
"Mobile" => $row['Mobile']
);
}
You can use:
$count = 0;
while($row = mysqli_fetch_array($result))
{
$send[$count] = $row;
$count ++;
}
Also you might want to use the table id as an array index, so you can access the records by ID later. In that case you can do:
while($row = mysqli_fetch_array($result))
{
$send[$row['id']] = $row;
}
You're declaring your array inside your loop. So it will reset it every time.
$send = array();
while($row = mysqli_fetch_array($result))
{
$send[] = array($row['Name'],$row['Email'],$row['Mobile']);
}

MSSQL returns multiple rows into array, explode into one array per row

I have an MSSQL query where it SELECTS all rows that meet a specific criteria. In PHP I want to fetch that array, but then I want to convert it into one array per row. So if my query returns 3 rows, I want to have 3 unique arrays that I can work with.
I'm not sure how to go about this. Any help would be greatly appreciated!
Thanks, Nathan
EDIT:
$query = "SELECT * FROM applicants WHERE applicants.user_id ='{$_SESSION['user_id']}'";
$query_select = mssql_query($query , $connection);
if (mssql_num_rows($query_select) == 2){
$message = '2 students created successfully';
}
$i = 0;
while($row = mssql_fetch_array($query_select)) {
$student.$i['child_fname'][$i] = $row['child_fname'];
$student.$i['child_lname'][$i] = $row['child_lname'];
$i++;
}
$query_array1 = $student0;
$query_array2 = $student1;
You will notice from the code above that I am expecting two rows to be returned. Now, I want to take those two rows and create two arrays from the results. I tried using the solution that was give below. Perhaps my syntax is incorrect or I didn't understand how to properly implement his solution. But any help would be greatly appreciated.
$query = mssql_query('SELECT * FROM mytable');
$result = array();
if (mssql_num_rows($query)) {
while ($row = mssql_fetch_assoc($query)) {
$result[] = $row;
}
}
mssql_free_result($query);
Now you can work with array like you want:
print_r($result[0]); //first row
print_r($result[1]); //second row
...
$i=0;
while( $row = mysql_fetch_array(query){
$field1['Namefield1'][$i] = $row['Namefield1'];
$field2['Namefield2'][$i] = $row['Namefield2'];
$field3['Namefield3'][$i] = $row['Namefield3'];
$i++;
}
or if you preffer an bidimensional array:
$i=0;
while( $row = mysql_fetch_array(query){
$result['Namefield1'][$i] = $row['Namefield1'];
$result['Namefield2'][$i] = $row['Namefield2'];
$result['Namefield3'][$i] = $row['Namefield3'];
$i++
}

PHP appending an array

I have some code that essentially does what I want but I always like to make it simpler and more efficient whenever possible so here I am.
Basically, I have a list of pages that each run an SQL query and pull X number of relevant records, appending each one to the former by saving to a text file that's then reopened for further processing, like so:
foreach($pages as $page){
$fp = fopen("$page.txt", 'w');fclose ($fp);
$result = $db->query("SELECT X, Y, Z FROM Table WHERE Pages LIKE '%$page%'");
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$v = $row['X'].'|'.$row['Y'].'|'.$row['Z'].';';
file_put_contents("$page.txt", $v, FILE_APPEND);
}
$data = file_get_contents("$page.txt");
$data = explode(';', $data);
}
Now while that gets the job done I was wondering what would be the better way of doing it, I've tried messing around with mixed results, was hoping this would work but it generates an error:
foreach($pages as $page){
$result = $db->query("SELECT X, Y, Z FROM Table WHERE Pages LIKE '%$page%'");
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$v = $row['X'].'|'.$row['Y'].'|'.$row['Z'].';' . $v;
$r = array("$page"=>"$v");
}
$data = join($r["$page"]);
$data = explode(';', $data);
}
Any ideas? Thanks
Your code's rather inefficient. You open a file and immediately close it, which is to create the file, I presume. You then use file_get_contents() to output to that file in append mode for every iteration of the loop. That means PHP has to re-open the file, jump to the end, write some text, then close it again. It's like going to the grocery store, buying something, driving home, going back to the store, buying another item, driving home, etc... A major waste of time.
Instead, try something like this:
foreach ($pages as $page) {
$result = $db->query(...) or die('db error...');
$data = array();
while($row = $result->fetchArray(...)) {
$data[] = $row; // append the fetched row to the $data array
}
... do something with $data here ...
}
After each while() loop completes, $data will be array that looks something like:
$data = array(
0 => array('X' => 'someval', 'Y' => 'otherval', 'Z' => 'otherotherval'),
1 => array('X' => etc.....),
etc...
)
if you need to write this $data array out to a file for processing elsewhere, you can use serialize() to output it as a string which can be trivially converted back to a native PHP array using unserialize().
You could also do it like:
$data = array();
foreach($pages as $page){
$result = $db->query("SELECT CONCAT(X, '|', Y, '|', Z) as `data` FROM Table WHERE Pages LIKE '%$page%'");
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$data[] = $row['data'];
}
}
Maybe a bit faster.
If I understood what you are trying to do correctly, then yes, there are much easier ways:
$data = array();
foreach($pages as $page){
$result = $db->query("SELECT X, Y, Z FROM Table WHERE Pages LIKE '%$page%'");
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$data[] = $row['X'].'|'.$row['Y'].'|'.$row['Z'];
}
}
And if I misunderstood, then I am sorry.
Edit
Fixed a little bug with the declaration of the $data array
What's you error?
I can see possible problems here
$v = $row['X'].'|'.$row['Y'].'|'.$row['Z'].';' . $v;
$r = array("$page"=>"$v");
remove the quote codes on $v, and define $v as a empty variable before the loop.

Create dynamic associated array from database fields

I got a database with 2 fields: amount and name.
I want to get all the data from the database (40 rows) and create an associated array out of it like this:
$arr = array("amount" => "12", "name" => "John");
How is this done dynamically in PHP? I am stuck.
If you're using the mysql_* function, you can do the following to get one row at a time:
$res = mysql_query("SELECT amount, name FROM mytable");
while ($row = mysql_fetch_assoc($res)) {
var_export($row); // outputs array ( 'amount' => '12', 'name' => 'John', )
}
To get all rows in a single array:
$customers = array();
$res = mysql_query("SELECT amount, name FROM customers");
while ($row = mysql_fetch_assoc($res)) {
$customers[] = $row;
}
Well, if you run your query, e.g.
$result = mysql_query('SELECT amount, name FROM table');
you can loop over the result like that:
$values = array();
while(($row = mysql_fetch_assoc($result))) {
$values[] = $row;//$row will be like array("amount" => "12", "name" => "John")
}
and you will have an array of arrays.
Check out mysql_fetch_assoc if you want to fetch database rows as an associative array (the documentation comes with a good example, too).
$data = $pdo->query('SELECT amount, name FROM ...')->fetchAll(PDO::FETCH_ASSOC);
That's it in PDO. And if you're not using PDO, well, that's your problem then...

PHP Sorting associative-array by other array

I need to sort an associative-array in the exact order of the content of another array.
The Arrays are retrieve by 2 separate sql-requests (stated below). The requests could not be combined to only one request, so I have to sort the second array into the order of the first one.
These are the arrays:
#Array which contains the id's in needed order
$sorting_array = array(1,2,3,8,5,6,7,9,11,10...);
#Array which contains the values for the id's, but in order of "id" ASC
$array_to_sort = array(
array("id" => "1", "name" => "text1", "help" => "helptxt2");
array("id" => "2", "name" => "text2", "help" => "helptxt2");
);
The SQL-Queries:
SQL-Ouery for $sorting_array: (the db-field 'conf' is setup as "text", maybe this is my problem so that I have to first explode and implode the entries before I could use it for the next query.)
$result = sql_query("select conf from config where user='me'", $dbi);
$conf = sql_fetch_array($result, $dbi);
$temp = explode(',', $conf[0]);
$new = array($temp[0], $temp[1], $temp[2], $temp[3],$temp[4],
$temp[5], $temp[6], $temp[7], $temp[8], $temp[9],
$temp[10], ...);#Array has max 30 entries, so I count them down here
$sorting_array = implode(',', $new);
SQL-Ouery for $array_to_sort:
$result = sql_query("SELECT id, name, helptxt
FROM table
WHERE id IN ($sorting_array)
AND language='english'");
while ($array_to_sort[] = mysql_fetch_array ($result, MYSQL_ASSOC)) {}
array_pop($array_to_sort);#deleting the last null entry
I could access $array_to_sort as follows to see the content one by one:
(if the lines below don't match the array above, than I mixed it up. However, the lines below is what brings the content)
echo $array_to_sort[0]["id"];
echo $array_to_sort[0]["name"];
echo $array_to_sort[0]["helptxt"];
But it is sorted by "id" ASC, but I need exactly the sorting as in $sorting_array.
I tried some things with:
while(list(,$array_to_sort) = each($sorting_array)){
$i++;
echo $array_to_sort . "<br>";
}
which only brings the Id's in the correct order, but not the content. Now I'm a bit confused, as I tried so many things, but all ended up in giving me the same results.
Maybe the sql-query could be done in one step, but I didn't brought it to work.
All results to my searches just showed how to sort ASC or DESC, but not what I want.
Furthermore I must confess that I'm relative new to PHP and MySQL.
Hopefully some one of you all could bring me back on track.
Many thanks in advance.
To fetch your results:
$result = mysql_query("SELECT id, name, helptxt
FROM table
WHERE id IN ($sorting_array)
AND language='english'");
$array_to_sort = array();
while ( ($row = mysql_fetch_assoc($result)) !== false ) {
// associate the row array with its id
$array_to_sort[ $row[ "id" ] ] = $row;
}
To display them in order of $sorting_array:
foreach ( $sorting_array as $id ) {
// replace the print_r with your display code here
print_r( $array_to_sort[ $id ] );
}
And a bonus tip for the code fetching $sorting_array:
$result = mysql_query("select conf from config where user='me'", $dbi);
$conf = mysql_fetch_array($result, $dbi);
$temp = explode(',', $conf[0]);
// limit to 30 ids
$new = array();
// no need to do this manually, use a loop
for ( $i = 0; $i < 30; ++$i )
$new[] = $temp[ 0 ];
$sorting_array = implode(',', $new);
Its a little hard to tell because there is a lot going on here, in the future you'll probably get better/more responses if you ask several simple questions and figure out yourself how to make the answers fit together.
Your best bet long term is going to be to restructure your SQL tablessuch that you can combine these query together. You can do what you're asking in PHP, but it's going to be slower than doing it in MySQL and much more complicated.
To do what you're asking (pretty slow in PHP):
$sorted = array();
foreach ( $sorting_array as $id )
{
foreach ( $array_to_sort as $values )
{
if ( $values['id'] == $id )
{
$sorted[] = $values;
break;
}
}
}
what I tend to do in such a situation is first to rearrange the array with the data. so the keys represent ids
In your case:
$array_to_sort_ids = array();
foreach ($array_to_sor as $item)
{
$array_to_sort_ids[$item['id']] = $item;
}
Then sorting is as simple as:
$array_sorted = array();
foreach ($sorting_array as $id)
{
$array_sorted[] = $array_to_sort_ids[$id];
}
This solution is quite efficient, since you only have 2 foreach loops.
EDIT!!!
As I couldn't edit my question anymore, I just like to state my solution this way:
The tip to rethink my database was what brought me to some testings and then I found the solution, with the following query:
$result = sql_query("SELECT id, name, helptxt
FROM table
WHERE id IN ($sorting_array)
AND language='english'
ORDER BY FIELD(id,$sorting_array)");
while ($array_to_sort[] = mysql_fetch_array ($result, MYSQL_ASSOC)) {}
array_pop($array_to_sort);#deleting the last null entry
Just the line:
ORDER BY FIELD(id,$sorting_array)
will do the trick. It orders the results the way you want, even if this means 1,4,2,3,9,7,...
Sometimes it's so easy, when you know where to look.
Thanks again!!!

Categories