Sort array by rule made of mysql select - php

Hello everyone I have really chalenging task I have to sort an array by condition with mysql select or by another array. Imagine something like that
$arrayINeedToSort = array(5,4,7,96,1,0,55);
// Dont know if it is important cause of next step
sort($arrayINeedToSort);
$arrayToCheckDuplicData = array();
foreach($arrayINeedToSort as $aid)
{
$sql = mysql_query("SELECT column FROM `some_table` WHERE arrayValueId = $aid ");
$num = mysql_num_rows($sql);
if($num)
{
echo $aid;
}
else
{
// skip this id cause it is not in array but i would like to push at the end of an array again sorted
if(in_array($aid,$arrayToCheckDuplicData))
{
echo $aid;
}
else
{
$arrayINeedToSort[] = $aid;
}
$arrayToCheckDuplicData[] = $aid;
}
}
Thats my idea, pushing array values to the end of acutal array with another simple array check but i am open to different/better ideas.
UPDATE //////////////////////////////////////////////
I need to see all ids so i cant skip them and I need them sorted.
TO BE MORE SPECIFIC i would liek to have input like this
1,4,96 (of values which are in database ) 0,5,7,55 (of values which are not in databse) at the end array will look like this
$outputSortedArray(1,4,96,0,5,7,55);

Could you please be more specific in what you want. On what is the input and what you want in your output.
If you need to sort the array $arrayINeedToSort then use sort function.
Give an example of the input and output array. Also the table with condition you wanted to check.
Check the following code and verify if this is what you want:
`
$arrayINeedToSort = array(5,4,7,96,1,0,55);
$in_cond = implode(",", $arrayINeedToSort);
$arrayToCheckDuplicData = array();
$result = mysql_query("SELECT column FROM `some_table` WHERE arrayValueId IN (" . $in_cond . ") ORDER BY arrayValueId ASC");
$num = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
if (in_array($row["arrayValueId"], $arrayINeedToSort)) {
echo $row["arrayValueId"];
}
else {
if (in_array($row["arrayValueId"], $arrayToCheckDuplicData)) {
echo $row["arrayValueId"];
}
$arrayToCheckDuplicData[] = $row["arrayValueId"];
}
}
`

You can use php array sorting functions: http://www.php.net/manual/en/array.sorting.php
There is also a function called array_unique, which is delete multiple values from an array.
If you want to sort the array in the MySQL query, use "ORDER BY ASC/DESC".

Related

How to store the value of index not the array itself in mysql query?

I need to be able to check if certain values are present in title_id, but as title_id's are index's it won't allow me to do this. Is there a way to store the values of the index without storing the array itself?
I have been searching for this answer for a long time but anything I search pulls up answers to different questions.
$selects = (array) null;
$res = mysqli_query($datab, "SELECT title_id FROM selects") or die($datab->error);
while ($datab = mysqli_fetch_assoc($res)) {
$selects[] = $datab;
}
///////////// part of a later query
if (!in_array($thisid, $selects)) {
$title[] = $datab;
$j++;
}
$selects is array of arrays, not array of title_id.
Try something like that:
while ($datab = mysqli_fetch_assoc($res)) {
$selects[] = $datab['title_id'];
}

Separating mysql fetch array results

i have a mysql table the contains an index id, a data entry and 10 other columns called peso1, peso2, peso3...peso10. im trying to get the last 7 peso1 values for a specific id.
like:
$sql = mysql_query("SELECT * FROM table WHERE id='$id_a' ORDER BY data DESC LIMIT 0, 7");
when i try to fetch those values with mysql_fetch_array, i get all values together.
example:
while($line = mysql_fetch_array($sql)) {
echo $line['peso1'];
}
i get all peso1 values from all 7 days together. How can i get it separated?
They will appear all together because you are not separating them as you loop through them.
for example, insert a line break and you will see them on separate lines
while($line = mysql_fetch_array($sql)) {
echo $line['peso1'] ."<br />";
}
You could key it as an array like so
$myArray = array();
$i = 1;
while($line = mysql_fetch_array($sql)) {
$myArray['day'.$i] = $line['peso1'];
$i++;
}
Example use
$myArray['day1'] // returns day one value
$myArray['day2'] // returns day two value
It's not clear what you mean by "separated" so I'm going to assume you want the values as an array. Simply push each row field that you want within your while loop onto an array like this:
$arr = array();
while($line = mysql_fetch_array($sql)) {
$arr[]=$line['peso1'];
}
print_r($arr);//will show your peso1 values as individual array elements

How do I insert values into an multidimensional-array, then show them?

I'm fairly new to php, and I don't know how to work with arrays very well. Here's the deal, I want to add into a multidimensional array three or more values I obtain from my database, then I want to sort them based on the timestamp (one of the values). After that, I want to show all of the sorted values. I can't seem to do this, here's the code
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, Order, Classification FROM exams WHERE (CurrentState = "Pending")';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if (mysql_num_rows($results) == 0) {
echo '<p>There\'s currently no patient on the waiting list.</p>';
return;
}
while ($rows = mysql_fetch_array($results)) {
extract($rows);
//now is the part that I don't know, putting the values into an array
}
// I'm also not sure how to sort this according to my $TargetTime
asort($sortedTimes);
//the other part I don't know, showing the values,
Thanks for the help!
Well, let's look at your code. First, you have a query that's returning a result set. I don't recommend using mysql_fetch_array because it's not only deprecated (use mysqli functions instead) but it tends to lend itself to bad code. It's hard to figure out what you're referencing when all your keys are numbers. So I recommend mysqli_fetch_assoc (be sure you're fully switched to the mysqli functions first, like mysql_connect and mysqli_query)
Second, I really dislike using extract. We need to work with the array directly. Here's how we do this
$myarray = array();
while ($rows = mysqlI_fetch_assoc($results)) {
$myarray[] = $rows;
}
echo $myarray[0]['ArrivalTime'];
So let's go over this. First, we're building an array of arrays. So we initialize our overall array. Then we want to push the rows onto this array. That's what $myarray[] does. Finally, the array we're pushing is associative, meaning all the keys of the row match up with the field names of your query.
Now, the sorting really needs to be done in your query. So let's tweak your query
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, `Order`, Classification
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime';
This way, when your PHP runs, your database now churns them out in the correct order for your array. No sorting code needed.
$arr = array();
while ($rows = mysql_fetch_array($results)) {
array_push ($arr, $row);
}
print_r($arr);
<?php
$queryWaitingPatients = ' SELECT ArrivalTime, TargetTime, Order, Classification, CurrentState
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime ';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if ($results -> num_rows < 1)
{
echo '<p>There\'s currently no patient on the waiting list.</p>';
}
else
{
while ($rows = mysqli_fetch_array($results))
{
$arrivaltime = $row['ArrivalTime'];
$targettime = $row['targettime'];
$order = $row['Order'];
$classification = $row['Classification'];
echo "Arrival: ".$arrivaltime."--Target time: ".$targettime."--Order: ".$order."--Classification: ".$classification;
}
}
echo "Done!";
//or you could put it in a json array and pass it to client side.
?>

PHP assign result from nested query into array

I need help in order to assign the results of a nested query into array. This is the scenario:
$Date_Collection = mysql_query("SELECT DISTINCT Date FROM TblDate");
while($date = mysql_fetch_array($Date_Collection)) // Loop through all the dates
{
$var_date = $date['Date'];
$result = mysql_query("select min(Speed) as Min_spd, max (Speed) as Max_spd, avg
(Speed) as Avg_spd from ... where Date= $var_date");
while($row = mysql_fetch_array($result))
{
echo "row[Min_spd]";
echo "row[Max_spd]";
echo "row[Avg_spd]";
}
}
The output from this query is like this:
Min_Spd |Max_Spd |Avg_Spd| Date|
12.0| 25.0| 20.4| 2012-10-01|
11.0| 28.0| 21.4| 2012-10-02|
10.0| 26.0| 23.4| 2012-10-05|
08.0| 22.0| 21.4| 2012-10-08|
I basically need to show the sum of Min_Spd, Sum of Max_spd, Sum of Avg_spd for all these dates. So, I thought that If I can assign these values into an array and later compute these sum from the array, it might be a good idea.
Can anyone please help me regarding this? Can I use an array to store the values and later access these values and calculate the sum of these values. If I can use an array, could anyone please show me the syntax of using array in PHP. I would really appreciate any help regarding this.
Is there any alternative way rather than using an array, such as creating a temporary table to save these values and later delete the temporary table. If a temporary table can be used, could you please show me how to do that. I could use the temptable for a single loop, but there is a nested loop and I don't exactly know what to do to create a temp table inside the nested loop to store all the values.
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
then later on you can do
foreach($data as $row) {
echo $row['Min_spd'];
echo ...
...
}
I don't know if the MySQL SUM function can be used to do that on te query, try it. But on this example, using arrays you should store the values and then use array_sum to return the sum of the elements. Something like this:
$min_spd = array();
$max_spd = array();
$avg_spd = array();
while($row = mysql_fetch_assoc($result))
{
$min_spd[] = $row['Min_spd'];
$max_spd[] = $row['Max_spd'];
$avg_spd[] = $row['Avg_spd'];
}
echo array_sum($min_spd);
It can also be done using variables to store and add the values:
$min_spd = 0;
$max_spd = 0;
$avg_spd = 0;
while($row = mysql_fetch_assoc($result))
{
$min_spd += $row['Min_spd'];
$max_spd += $row['Max_spd'];
$avg_spd += $row['Avg_spd'];
}
echo $min_spd;
I would first of all save yourself a nested query by doing the first query as:
$result = mysql_query("select Date, min(Speed) as Min_spd, max (Speed) as Max_spd, avg(Speed) as Avg_spd from ... group by Date")
And then create a running total for the sums as you're looping through each row:
$sumMinSpeeds=0;
$sumMaxSpeeds=0;
$sumAvgSpeeds=0;
while($row = mysql_fetch_array($result))
{
echo row['Min_spd'];
echo row['Max_spd'];
echo row['Avg_spd'];
$sumMinSpeeds += $row['Min_spd'];
$sumMinSpeeds += $row['Max_spd'];
$sumMinSpeeds += $row['Avg_spd'];
}
echo $sumMinSpeeds;
echo $sumMaxSpeeds;
echo $sumAvgSpeeds;
Instead of doing several MySQL queries in a loop, consider constructing such a query, which will return all the results you need.
SQL
First of all, it would make sense to use the GROUP SQL construct.
SELECT
s.Date date,
MIN(s.Speed) min,
MAX(s.Speed) max,
AVG(s.Speed) avg
FROM speed_table s
WHERE s.Date IN (SELECT DISTINCT d.Date FROM date_table d)
GROUP BY s.Date
It is important to understand what each part of this query does. If you run into any problems, consult the MySQL reference manual.
PHP
Forget about using mysql_* functions: they are deprecated and better implementations have emerged: PDO and mysqli. My example uses PDO.
try {
$dbh = new \PDO('mysql:dbname=my_db_name;host=127.0.0.1', 'dbuser', 'dbpass');
} catch (\PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = '...'; // This is the query
$stmt = $pdo->prepare($sql);
$stmt->execute();
You can now either iterate over the returned result set
while ($row = $stmt->fetch()) {
printf("%s; %s; %s; %s\n", $row['date'], $row['min'], $row['max'], $row['avg']);
}
or have the Statement object return the whole array by using
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC);

Get rows from mysql table to php arrays

How can i get every row of a mysql table and put it in a php array? Do i need a multidimensional array for this? The purpose of all this is to display some points on a google map later on.
You need to get all the data that you want from the table. Something like this would work:
$SQLCommand = "SELECT someFieldName FROM yourTableName";
This line goes into your table and gets the data in 'someFieldName' from your table. You can add more field names where 'someFieldName' if you want to get more than one column.
$result = mysql_query($SQLCommand); // This line executes the MySQL query that you typed above
$yourArray = array(); // make a new array to hold all your data
$index = 0;
while($row = mysql_fetch_assoc($result)){ // loop to store the data in an associative array.
$yourArray[$index] = $row;
$index++;
}
The above loop goes through each row and stores it as an element in the new array you had made. Then you can do whatever you want with that info, like print it out to the screen:
echo $row[theRowYouWant][someFieldName];
So if $theRowYouWant is equal to 4, it would be the data(in this case, 'someFieldName') from the 5th row(remember, rows start at 0!).
$sql = "SELECT field1, field2, field3, .... FROM sometable";
$result = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
echo $array[1]['field2']; // display field2 value from 2nd row of result set.
The other answers do work - however OP asked for all rows and if ALL fields are wanted as well it would much nicer to leave it generic instead of having to update the php when the database changes
$query="SELECT * FROM table_name";
Also to this point returning the data can be left generic too - I really like the JSON format as it will dynamically update, and can be easily extracted from any source.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo json_encode($row);
}
You can do it without a loop. Just use the fetch_all command
$sql = 'SELECT someFieldName FROM yourTableName';
$result = $db->query($sql);
$allRows = $result->fetch_all();
HERE IS YOUR CODE, USE IT. IT IS TESTED.
$select=" YOUR SQL QUERY GOOES HERE";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
THANKS

Categories