php - How to order by a segment of preg_match_all results? -
i'm using php generate list of references text doing preg_match_all search on database table. here php code:
$query = "select primary_tag,display_short_title,content topics;"; $result = mysql_query($query) or die("query failed : " . mysql_error()); $num_results = mysql_num_rows($result); ($i = 0; $i < $num_results; $i++) { $row = mysql_fetch_array($result); if (preg_match_all("/(\<i\>u\<\/i\>|u) [0-9]{1,2}\.[0-9]{1,7}/", $row["content"], $matches)) { foreach ($matches[0] $match) { $match = ltrim(strip_tags($match), "u "); echo '<p class="textmark_result">' . $match; echo ' <a href="../essays/topic.php?shorttitle=' . $row["primary_tag"] . '">' . $row["display_short_title"] . '</a>'; echo "</p>\n"; } } } and results (viewing source) this:
<p class="textmark_result">15.1737 <a href="../essays/topic.php?shorttitle=medicine">medicine</a></p> <p class="textmark_result">5.678 <a href="../essays/topic.php?shorttitle=science">science</a></p> <p class="textmark_result">14.665 <a href="../essays/topic.php?shorttitle=science">science</a></p> in resulting web page, want order results decimal in middle, $match in code, (in example) 5.678 comes first, 14.665, 15.1737. there way that?
thank you!
three steps do:
- get matches , add them array -
floatval($match)key. - sort resulting array key (floats sort numeric value, strings sort characters - therefore
floatval(...)). - iterate on sorted array
code:
// mysql stuff goes here ... // create empty array $results = array(); ($i = 0; $i < $num_results; $i++) { $row = mysql_fetch_array($result); if (preg_match_all("/(\<i\>u\<\/i\>|u) [0-9]{1,2}\.[0-9]{1,7}/", $row["content"], $matches)) { foreach ($matches[0] $match) { $match = ltrim(strip_tags($match), "u "); // array pseudo key float value of $match // add '_key' member usort() $row['_key'] = floatval($match); $results[] = $row; } } } // sort array float key usort($results, function($a, $b) { if($a['_key'] == $b['_key']) return 0; elseif($a['_key'] > $b['_key']) return 1; else return -1; }); // ... display stuff in order foreach($results $row) { echo '<p class="textmark_result">' . (string)$row['_key']; echo ' <a href="../essays/topic.php?shorttitle=' . $row["primary_tag"] . '">' . $row["display_short_title"] . '</a>'; echo "</p>\n"; }
Comments
Post a Comment