PHP array out of order - php

I am pulling information from a database- from two different tables. The origins of the data is a single archival document- so each row from the two tables has a unique value- line number.
So the code is as follows
//get data about the report as a whole.
$sql = "SELECT * FROM reports_list WHERE report_key ='" . $report_key . "'";
$report_data = $wpdb->get_results ($sql);
//Time to start building the file to go out.
$total_report = array();
foreach($reports_in_db as $key)
{
$total_report [$key->line_number] = $key;
}
// get subtitles/abstract
$sql = "SELECT line_number, field_text FROM subtitle_abstract_summary WHERE report_key = '" . $report_key . "'";
$abs_sums = $wpdb->get_results ($sql);
//now for a series of conditional things
if (empty($abs_sums))
{
//echo "subtitles/abstracts"
}
else
{
foreach ($abs_sums as $key)
{
$total_report [$key->line_number] = $key;
}
}
So what I expected to happen, is to create an array where the main data rows have the subtitles rows interspersed. What actually happens is that $total_report has all the main data rows, followed by all the subtitles rows. When I print_r the array, they're not in the order I expect.
for example, if the data rows are row 1-200, and the subtitle rows are 121, 161, and 181, this code produces an array that has elements 1-120, 122-160, 162-180, then 121,161 and 181 in that order.
Currently, the elements are WPDB objects. If possible, I'd like to be able to just get them in the right order. If there's also a simple way to just sort by the element number, that's okay too.
I've tried doing sort() on $total_report- but that sorted by the alphabetical value of the first field of the object..
I'm honestly just puzzled why the array doesn't have the elements in the order I thought they'd be in.
Thanks

Use ksort() to sort array by keys. And SORT_NUMERIC flag so it would sort it as numbers:
<?php
...
ksort($total_report,SORT_NUMERIC);
...
?>

Related

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

Selecting different items in a fetch array

When using mysql_fetch_array, i pass the array data to a separate variable. My question is how do i access the different items held in that array by their position?
Preferably i want to call each item in turn have a calculation run on that item and if the result is the lowest number so far, pass that data to a variable.
Any help is appreciated, thanks.
<?php
$query = "SELECT postcode FROM freelance ORDER BY id";
$result = mysql_query($query);
while($postcode = mysql_fetch_array($result)) {
echo "<span>" . $postcode['postcode'] . "</span></br>";
}
?>
Instead of echo out all postcodes how would i define to only output the third item in the array
Solution 1:
You can display them with a foreach in the while:
foreach($postcode as $data) {
echo $data;
}
Solution 2:
You can call them by position (starts with 0):
$postcode[0]
$postcode[1]
$postcode[2]
...
Read more about array's : http://www.php.net/manual/de/language.types.array.php
When you call mysql_fetch_array, you are getting the results of the next row returned by your query. In this case, your query is returning a result set with one column, postcode, and many rows (presumably). Your while loop is just getting each row's postcode value and echoing it in a <span>.
EDIT: I have changed my code example in reponse to the OP's comment.
I am not really familiar with what it is you are trying to do, but hopefully my example makes some sense (you will have to fill in some blanks with your code). For one, I don't think you need to store the results from the database into one big array and then go through each record to determine the lowest distance. You are already looping through each record in your while loop, make use of it!
<?php
$inputcoords = //I assume that you already have the coordinates for the input postal code somewhere
$query = "SELECT postcode FROM freelance ORDER BY id";
$result = mysql_query($query);
while($postcode = mysql_fetch_array($result)) {
$curpostcode = $postcode['postcode'];
$curcoords = //calculation/function/something that calculates the current coordinates from $curpostcode
$distance = //Haversine formula using $curcoords and $inputcoords (you'll have to figure this part out)
if (!isset($lowest) || $distance < $lowest) {
$lowest = $distance;
//optional: if you want to keep track of which postal code gave the shortest distance...
$lowestpostcode = $curpostcode;
}
}
//go on to use the calculated distances for something...
?>
Also, as a side note, mysql_* functions are deprecated. If at all possible, you should switch to mysqli or PDO.

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.
?>

Sum the entries of items with the same index ID in a multi-dimensional array?

I have a multidimensional array that contains a variable number of sub arrays.
Each sub-array contains a list of numeric keys and values.
I have a separate array that is the result of an "array_intersect_key" function against the multidimensional array that contains only the keys that exist in each sub-array.
I want to walk through the intersect_key array and for each item in it sum the values associated with the matching keys within the multidimensional array and then take the total and use that to replace the value associated with the key in the intersect_key array while maintaining the same index id.
The key in each array relates to the id of an article in the database, the value associated with the key is how many times a certain word appears in that article. I'm trying to add together all the word counts relating to each article so I can then order them by relevance.
The code that creates the arrays:
$arr_articles = array();
foreach($arr_words as $wordid => $word) {
$query = "SELECT articleid,wordcount FROM index_wordsearch AS iws WHERE iws.keywordid = '$wordid'";
$articlesearch = mysql_query($query);
if (!$articlesearch) {
die('Unable to search for articles matching the specified words: '.mysql_error());
} else {
$arr_ids = array();
while ($row = mysql_fetch_assoc($articlesearch)) {
$articleid = $row['articleid'];
$wordcount = $row['wordcount'];
$arr_ids["$articleid"] = "$wordcount";
}
$arr_aticles[] = $arr_ids;
}
}
$arr_matches = call_user_func_array('array_intersect_key',$arr_articles);
I've started trying to tackle this by using the call_user_func_array() call again to branch out to a custom function but this approach doesn't feel right.
Maybe replace
$arr_ids["$articleid"] = "$wordcount";
with
if (!isset($arr_ids[$articleid]))
$arr_ids[$articleid] = 0;
$arr_ids[$articleid] += $wordcount;
I suggest for performance, that you retrieve all required data with a single SQL query (maybe using WHERE iws.keywordid IN (...)) and then process results in a PHP loop. Generally speaking, putting an SQL query in a loop should be avoided.
EDIT suggestion:
$query = "SELECT articleid, SUM(wordcount) AS wordcount
FROM index_wordsearch
WHERE keywordid IN (".implode(", ", array_keys($arr_words)).")
GROUP BY articleid";
$articlesearch = mysql_query($query) or die('Unable to search for articles matching the specified words: '.mysql_error());
$arr_articles = array();
 
while ($row = mysql_fetch_assoc($articlesearch))
$arr_articles[$row['articleid']] = $row['wordcount'];
print_r($arr_articles); // shows total matched word count for each article id

php & mysql - loop through columns of a single row and passing values into array

I have a mysql table with columns id, f1, f2, f3, ..., f20 where id is productID and f1,...f20 are product features. Depending on each product, some might have all, none or only some columns filled.
Each column holds a delimited string like a#b#c#d where a,b,c,d are values in different languages (a=english, b=french etc)
I need to select a row by it's id, explode each column's value (f1,f2...) with '#' in order to get the language part I need and then pass the values to an array in order to use in my product spec page.
How do I loop through the fetched row (i'm using $row = my_fetch_array) and put the exploded value into a one dimension array like $specs=('green', 'M', '100', 'kids'...) etc?
PS:I know, is complicated but I cant come up with a better idea right now.
Try this:
$result = mysql_query("...");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$arr = array();
foreach ($row as $k=>$v)
{
$features = explode("#", $v);
$value = $features[1]; // get the specific language feature
$arr[] = $value;
}
$specs = join(", " , $arr);
}
Not sure this is the best way togo but you could define an array with your langs, then access the result by lang
<?php
$langs=array('eng'=>0,'fr'=>1,'ger'=>2,'geek'=>3);
while ($row=mysql_fetch_assoc($result)) {
$specs=explode('#',$row['f1']);
$other=explode('#',$row['f2']);
...
}
//Get lang from cookie that you could set elsewhere
$lang=(isset($_COOKIE['lang']))?$_COOKIE['lang']:'eng';
echo $specs[$langs[$lang]];
?>
My solution for how I understand you question:
// Make a MySQL Connection
$sQuery = "SELECT f1,f2,... FROM table WHERE id = ...";
$oResult = mysql_query($sQuery) or die(mysql_error());
//Fetch assoc to use the column names.
$aRow = mysql_fetch_assoc($oResult);
//Prepare the product properties array
$aProductProperties = array("English"=>array(),"French"=>array(),"Dutch"=>array());
//Loop over all the columns in the row
foreach($aRow as $sColName=>$sColVal){
//Explde the column value
$aExplodedCol = explode("#",$sColVal);
//The code below could be nicer when turned into a looped that looped over every language,
//But that would make the code less readable
$aProductProperties['English'][$sColName] = $aExplodedCol[0];
$aProductProperties['French'][$sColName] = $aExplodedCol[1];
$aProductProperties['Dutch'][$sColName] = $aExplodedCol[2];
}
//Done, you should now have an array with all the product properties in every language

Categories