I have got the following, but in the results is a long string, contained within that string is a server name which I am wanting to sort the results by, is this possible?
<?php
$dbQuery = mysql_query("SELECT * FROM opencall where cust_id = 'user.name#jpress' and status < 6 order by fixbyx asc") or die(mysql_error());//find call ref of open call with correct id
while ($PRTGdbresults = mysql_fetch_array($dbQuery)){
$SplitText = explode("\n", $probtext); //split the string by line break
echo'<div class="row">';
echo'<div class="inf_div" title="Current Server">';
echo $SplitText[1]; //this is the server name I wish to sort by
echo'</div></div>';
}
?>
You can define your own function for sorting and then use this function with the usort sorting function.
Using the code you gave I will simply compare the strings of the server names and sort them in alphabetical order. Here is the code;
<?php
$dbQuery = mysql_query("SELECT * FROM opencall where cust_id = 'user.name#jpress' and status < 6 order by fixbyx asc") or die(mysql_error());
$results = array();
while ($PRTGdbresults = mysql_fetch_array($dbQuery)){
array_push($results,$probtext);
}
usort($results, "sortProbtext");
foreach($results as $key => $probtext){
$SplitText = explode("\n", $probtext);
echo'<div class="row">';
echo'<div class="inf_div" title="Current Server">';
echo $SplitText[1];
echo'</div></div>';
}
function sortProbtext($a, $b){
$SplitTextA = explode("\n", $a);
$SplitTextB = explode("\n", $b);
if ($SplitTextA[1] == $SplitTextB[1] ) {
return 0;
}
return ($SplitTextA[1] < $SplitTextB[1] ) ? -1 : 1;
}
?>
Related
I have a mysql table(request) here:
request:
r_id item_no
1 1
13 10
22 20
33 30
55 40
Now, I'm using php to take r_id out using mysql_fetch_array() and try to put mysql_fetch_array() result in to a string also split the string by comma.
<?php
include('config.php'); //connect to mysql
function f(){
$sql = "SELECT r_id FROM `request` ";
$result=mysql_query($sql);
$string = '';
$i = 0;
while ($row = mysql_fetch_array($result)) {
$string .= $row[$i];
}
$newstring = implode(", ", preg_split("/[\0-9]+/", $string));
return $newstring ;
}
$get=f();
echo $get;
?>
But I cannot get the right string form my php code.
I want to get the string like
1,13,22,33,55
How can I fix the problem?
You don't need to split that and implode, just do this:
while ($row = mysql_fetch_array($result)) {
$string .= $row[$i].',';// append comma after each value you append to the string
}
return substr($string,0,-1);// cut off the trailing comma from the final string
<?php
include('config.php'); //connect to mysql
function f(){
$sql = "SELECT GROUP_CONCAT(r_ID) FROM `request` ";
$result=mysql_query($sql);
return $result ;
}
$get=f();
echo $get;
?>
Try my updated answer:
$sql = "SELECT r_id FROM `request` ";
$result=mysql_query($sql);
$string = '';
$i = 0;
while ($row = mysql_fetch_array($result)) {
$string .= $row[$i].",";
}
return $string ;
}
$array = array();
while(...){
$array = $row[$i]; //first you need array
}
$string = implode(",",$array); //now you have your string
I have text :
$a = I wanna eat apple , and banana .
I wanna get every words and punctuation of that sentence :
$b = explode(' ', strtolower(trim($a)));
the result of explode is array.
I have a words table on db that has fields : id, word and typewords all in lowercase. but for punctuation there are no exist in db.
I wanna search every words in db to take the type of words, so the final result that i want to get is :
words/typeofwords = I/n wanna/v eat/v apple/n ,/, and/p banana/n ./.
here's the code :
function getWord ($word){
$i = 0 ;
$query = mysql_query("SELECT typewords FROM words WHERE word = '$word' ");
while ($row = mysql_fetch_array($query)) {
$word[$i] = $row['typewords'];
$i++;
}
return $word;
}
echo $b.'/'.getWord($b);
but it doesn't work, please help me, thanks !
Try with this:
function getWord($words){
$association = array();
foreach($words as $word)
{
$query = mysql_query("SELECT typewords FROM words WHERE word = '$word' ");
if($row = mysql_fetch_array($query))
$association[$word] = $row['typewords'];
elseif(preg_match('/[\.\,\:\;\?\!]/',$word)==1)
$association[$word] = $word;
}
return $association;
}
$typewords = getWord($b);
foreach($b as $w)
echo $w.'/'.$typewords[$w];
function getWord($word){
// concat the word your searching for with the result
// http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat
$query = mysql_query("SELECT CONCAT(word,'/',typewords) as this_result FROM words WHERE word = '$word' ");
$row = mysql_fetch_array($query);
return $row['this_result']." "; // added a space at the end.
}
// loop through the $b array and send each to the function
foreach($b as $searchword) {
echo getWord($searchword);
}
You assume the function parameter to be an array, but it is a string.
Edit: In your function you treat $word as an array as well as a string. Decide what you want and recode your function.
I have a table that I need to find "top trusted builder" from, Trusts are separated by " ; ", So I need to pull all the data, explode the usernames, order and count them, and Im stuck on finally outputting the top username form the array, I have posted up the full segment of PHP, because im sure there has to be a much better way of doing this.
<?php
$GTB = $DBH->query('SELECT builders from griefprevention_claimdata where builders <> ""');
$GMCB->setFetchMode(PDO::FETCH_ASSOC);
$buildersarray = array();
while($row = $GTB->fetch()) {
$allbuilders = explode(";", $row['builders']);
for($i = 0; $i < count($allbuilders); $i++)
{
$buildersarray[] = $allbuilders[$i];
}
}
echo "<pre>";
print_r(array_count_values(array_filter($buildersarray)));
echo "</pre>";
?>
Outputs
Array
(
[username1] => 4
[username2] => 1
[username3] => 1
)
You can return the array from the array_count_values command into a new array called $topbuilders, and then echo out the current (first) record:
$topbuilders = array_count_values(array_filter($buildersarray));
echo current(array_keys($topbuilders)).', Rank = '.current($topbuilders);
current() will return the first item in an associative array.
Instead of using array_count_values() it would be better to use the names as the key to a frequency array:
$GTB = $DBH->query('SELECT builders from griefprevention_claimdata where builders <> ""');
$result = array();
while (($builders = $GTB->fetchColumn()) !== false) {
foreach (explode(";", $builders) as $builder) {
if (isset($result[$builder])) {
$result[$builder]++;
} else {
$result[$builder] = 1;
}
}
// sort descending based on numeric comparison
arsort($result, SORT_NUMERIC);
echo "Name = ", key($result), " Count = ", current($result), "\n";
I am trying to get a series of 'titles' from a database, and place them in an array as individual strings for each title. Currently I am using this code
mysql_select_db($database_Algorox_Build, $Algorox_Build);
$query_getLatest = "SELECT title FROM news ORDER BY title ASC";
$getLatest = mysql_query($query_getLatest, $Algorox_Build) or die(mysql_error());
$totalRows_getLatest = mysql_num_rows($getLatest);
$latestNews = array();
for ($i = 0; $i <= $totalRows_getLatest; ++$i) {
$row_getLatest = mysql_fetch_assoc($getLatest);
$latestNews[] = array_values($row_getLatest);
}
and when I call them individually using
echo $latestNews[0][0];
I get the string value.
However, I would like to place these strings in to a single array, thereby generating an array of strings. I have tried this:
$latestNews = array();
$extractNews = array();
for ($i = 0; $i <= $totalRows_getLatest; ++$i) {
$row_getLatest = mysql_fetch_assoc($getLatest);
$latestNews[] = array_values($row_getLatest);
$extractNews[] = $latestNews[i][0];
}
but it doesn't return the string in the output extractNews array.
What am I doing wrong?
Thanks
Is this what you are looking for?
mysql_select_db($database_Algorox_Build, $Algorox_Build);
$query_getLatest = "SELECT title FROM news ORDER BY title ASC";
$getLatest = mysql_query($query_getLatest, $Algorox_Build) or die(mysql_error());
$latestNews = array();
while($row = mysql_fetch_assoc($getLatest)) {
$latestNews[] = $row['title'];
}
echo "<pre>" . print_r($latestNews,1) . "</pre>";
WATCH OUT
Please do not use the mysql_* functions anymore. They are deprecated and won't be supported in >= php 5.5. Switch to mysqli_* or PDO.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to sort the results of this code?
Im making a search feature which allows a user to search a question and it will show the top 5 best matching results by counting the number of matching words in the question.
Basically I want the order to show the best match first which would be the question with the highest amount of matching words.
Here is the code I have.
<?php
include("config.php");
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //User enetered data
$search_term = str_replace ("?", "", $search_term); //remove any question marks from string
$search_count = str_word_count($search_term); //count words of string entered by user
$array = explode(" ", $search_term); //Seperate user enterd data
foreach ($array as $key=>$word) {
$array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
}
$q = "SELECT * FROM posts WHERE " . implode(' OR ', $array); //Query to select data with word matches
$r = mysql_query($q);
$count = 0; //counter to limit results shown
while($row = mysql_fetch_assoc($r)){
$thetitle = $row['title']; //result from query
$thetitle = str_replace ("?", "", $thetitle); //remove any question marks from string
$title_array[] = $thetitle; //creating array for query results
$newarray = explode(" ", $search_term); //Seperate user enterd data again
foreach($title_array as $key => $value) {
$thenewarray = explode(" ", $value); //Seperate each result from query
$wordmatch = array_diff_key($thenewarray, array_flip($newarray));
$result = array_intersect($newarray, $wordmatch);
$matchingwords = count($result); //Count the number of matching words from
//user entered data and the database query
}
if(mysql_num_rows($r)==0)//no result found
{
echo "<div id='search-status'>No result found!</div>";
}
else //result found
{
echo "<ul>";
$title = $row['title'];
$percentage = '.5'; //percentage to take of search word count
$percent = $search_count - ($search_count * $percentage); //take percentage off word count
if ($matchingwords >= $percent){
$finalarray = array($title => $matchingwords);
foreach( $finalarray as $thetitle=>$countmatch ){
?>
<li><?php echo $thetitle ?><i> <br />No. of matching words: <?php echo $countmatch; ?></i></li>
<?php
}
$count++;
if ($count == 5) {break;
}
}else{
}
}
echo "</ul>";
}
?>
When you search something it will show something like this.
Iv put the number of matching words under each of the questions however they are not in order. It just shows the first 5 questions from the database that have a 50% word match. I want it to show the top 5 with the most amount of matching words.
What code would I need to add and where would I put it in order to do this?
Thanks
Here's my take on your problem. A lot of things have been changed:
mysql_ functions replaced with PDO
usage of anonymous functions means PHP 5.3 is required
main logic has been restructured (it's really hard to follow your result processing, so I might be missing something you need, for example the point of that $percentage)
I realize this might look complicated, but I think that the sooner you learn modern practices (PDO, anonymous functions), the better off you will be.
<?php
/**
* #param string $search_term word or space-separated list of words to search for
* #param int $count
* #return stdClass[] array of matching row objects
*/
function find_matches($search_term, $count = 5) {
$search_term = str_replace("?", "", $search_term);
$search_term = trim($search_term);
if(!strlen($search_term)) {
return array();
}
$search_terms = explode(" ", $search_term);
// build query with bind variables to avoid sql injection
$params = array();
$clauses = array();
foreach ($search_terms as $key => $word) {
$ident = ":choice" . intval($key);
$clause = "`title` LIKE {$ident}";
$clauses []= $clause;
$params [$ident] = '%' . $word . '%';
}
// execute query
$pdo = new PDO('connection_string');
$q = "SELECT * FROM `posts` WHERE " . implode(' OR ', $clauses);
$query = $pdo->prepare($q);
$query->execute($params);
$rows = $query->fetchAll(PDO::FETCH_OBJ);
// for each row, count matches
foreach($rows as $row) {
$the_title = $row->title;
$the_title = str_replace("?", "", $the_title);
$title_terms = explode(" ", $the_title);
$result = array_intersect($search_terms, $title_terms);
$row->matchcount = count($result);
}
// sort all rows by match count descending, rows with more matches come first
usort($rows, function($row1, $row2) {
return - ($row1->matchcount - $row2->matchcount);
});
return array_slice($rows, 0, $count);
}
?>
<?php
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING);
$best_matches = find_matches($search_term, 5);
?>
<?php if(count($best_matches)): ?>
<ul>
<?php foreach($best_matches as $match): ?>
<li><?php echo htmlspecialchars($match->title); ?><i> <br/>No. of matching words: <?php echo $match->matchcount; ?></i></li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<div id="search-status">No result found!</div>
<?php endif; ?>
Try adding asort($finalarray); after your $finalarray = array($title => $matchingwords); declaration:
...
if ($matchingwords >= $percent){
$finalarray = array($title => $matchingwords);
asort($finalarray);
....
It should sort your array Ascending by the Values