So, I'm trying to display an associative array generated from a table in my database. These are the steps I'm trying to accomplish:
Get result set from database that's already sorted in certain order based on a column(Ascending/Descending).
Add/Transfer/Append each record/row in the result set to another array. While in the process of appending, check if the array we are adding records has a value(based on a different column) similar to the record we are currently adding.
If the value we are checking for is already there, skip appending. If not, append the record and continue with the loop until the end of the result set.
This is the sample data I am working with, tbl_user_details:
Sample data
As you can see, it has been sorted in descending order based on the user_pos column. If you look at the user_id column, we have duplicate values. What I am trying to achieve is adding each record to an array and skipping the duplicate values based on the user_id column.user_id = 4 and user_pos = 7. Next will be ada with user_id = 2 and user_pos = 6. The next record which we are not going add is woz with user_id = 2 and user_pos = 5 because we already have someone with user_id = 2. So, we skip to adding ghopper who has user_id = 3 and user_pos = 4... and so forth. I think this example explains the flow of data I need displayed.
I've tried some simple code to get this done which it's clearly not working. Here is the snippet:
$query3 = "SELECT * FROM `user_details` ORDER BY `user_details`.`user_pos` DESC";
$user_set = mysqli_query($connection, $query3);
if (!$user_set) {
die("Database query failed.".mysqli_error($connection));
}
$user_arr = array();
while ($row = mysqli_fetch_assoc($user_set)) {
if (in_array($row["user_id"], $user_arr)) {
continue; // skip if we already have this value in array
}
$user_arr[] = $row;
}
The records that should be displayed are of aswartz, ada, ghopper and rasmusl. The rest are ignored. When I display the data in '$user_arr[]' using the foreach loop method, it still displays the whole data as it is on the table.
It will become multi dimensional array when you add row to array so you cant check user_id in it. There are many other solutions to check unique record but One simplest solution is to assign user_id as key then check key for duplication
while ($row = mysqli_fetch_assoc($user_set)) {
if (isset($user_arr[$row["user_id"]])) {
continue; // skip if we already have this value in array
}
$user_arr[$row["user_id"]] = $row;
}
Note: If you want unique records only then you can use DISTINCT in query
Use another $tempArr which will contain only user_id to in in_array, In you code you are checking user_id against array or whole row which is user details not just against user_ids
$user_arr = array();
$tempArr = array();
while ($row = mysqli_fetch_assoc($user_set)) {
if (in_array($row["user_id"], $tempArr)) {
continue; // skip if we already have this value in array
}
$user_arr[] = $row;
$tempArr[] = $row["user_id"];
}
Related
How do i filter an array list in php to skip one row that has already been added where one of its column value is repited.
I have tried using in_array to filter and array_exist
$getRoom = mysqli_query($con, $sql);
$json_array = array();
while($row=mysqli_fetch_assoc($getRoom)) {
if (in_array($row['hotel_name'], $json_array)) {
}
else {
$json_array = $row;
}
}and
echo json_encode($json_array);
I want hotel name and one of the rooms found
The code (as it is provided right now) is not actually adding a line to $json_array, it's just replacing the current value with the current row. $json_array = $row; needs to become $json_array = $row[];
The second issue is that in_array isn't going to recursively search the second level of array so it's never going to find $row['hotel_name']. I would recommend restructuring your arrays a bit (depending on how your downstream code is going to use them) to something more like this:
while($row=mysqli_fetch_assoc($getRoom)) {
$json_array[$row['hotel_name']][] = $row;
}
This will group your data so that each hotel is only listed once in the top level array but you keep all of the details about the various rooms. If you really only need the distinct hotel names then you should restructure your database query to only return unique values using a distinct clause.
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
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
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
I'm putting values from the database inside a while into an array. Now I wan't to check - inside the while - if the next ID is the same as just outputed. If it isn't my thought is to put the ID inside the array.
Is there any possibility to do this? To check a the next output of a query in a while?
$result = mysql_query("SELECT * FROM $postmeta ORDER BY post_id ASC")
or die(mysql_error());
$basArray = array();
while($row = mysql_fetch_array( $result )) {
$innerArray[$row['meta_key']] = $row['meta_value'];
$basArray[$row['post_id']] = $innerArray;
// Above post_id I want to check if it is the same as the "next coming"
}
Greetings
I would usually just store the most recent ID in a variable, and check it at the top of the while loop. In pseudocode, like this:
$old_row_id = -1; // any value that can't legitimately appear
while ($row = fetch_array($result)) {
if ($old_row_id == $row['id']) {
// logic to follow if IDs are the same
} else {
// logic to follow if IDs are different
}
// logic to follow in either case, if any
$old_row_id = $row['id']; // update variable for the next run through
}
If you really do need to change the behaviour for a particular row according to what happens in the next row, I recommend that you actually effect that change in the following run through the loop, when you check the new row ID against the old one.
Alternatively, you can loop through the resultset twice: the first time putting the rows into a 2-dimensional array so that you can easily reference difference rows by number. Then the second time, you actually do whatever you wanted to do in the first place, and you can reference "the next row" by using [$i + 1] rather than [$i]. (Of course then you have to be careful about the final row, because then the offset [$i + 1] doesn't work.)