I have a php script that generates a few divs with one class each, like this:
<div class="1">...</div>
<div class="2">...</div>
<div class="1">...</div>
<div class="3">...</div>
<div class="2">...</div>
How can I sort them efficiently and as quickly as possible using php? What is the best sorting algorithm for this? There are always about 2 to 5 divs to sort.
The result should be:
<div class="1">...</div>
<div class="1">...</div>
<div class="2">...</div>
<div class="2">...</div>
<div class="3">...</div>
If you can't do it with javascript ... order before rendering the page. Example with a kind of MVC:
So:
<?php
// $data is filled BDD or any source
$output = [];
foreach( $data as $row ) {
$content = '<div class="' . $row['my-class'] . '">...</div>';
$output[] = ['key' => $row['my-class'], 'content' => $content];
}
usort($output, function($a, $b) {
return $a['key'] < $b['key'];
});
foreach( $output as $row ) {
echo $row['content'];
}
I used a 2D array. Of course, you could use another ways as:
$output = [];
foreach( $data as $row ) {
$key = $row['my-class'] . '-' . count($output);
$output[$key] = $content;
}
ksort($output);
foreach( $output as $row ) {
echo $row;
}
If for some reason you can´t use the variable that gives the name to your class, I would use a regex to accomplish this
$html='
<div class="1">...</div>
<div class="2">...</div>
<div class="1">...</div>
<div class="3">...</div>
<div class="2">...</div>
';
$regex="/<div.*class=\"(.*?)\">.*?<\/div>/";
$numItems = preg_match_all($regex, $html, $matches);
$arr = array();
for ( $i = 0; $i < $numItems; $i++ ){
$arr[$i] = array();
$arr[$i]["code"] = $matches[0][$i];
$arr[$i]["className"] = $matches[1][$i];
}
usort($arr, function($a, $b){ return strcmp($a["className"], $b["className"]); });
$arr = array_map(function($a){ return $a["code"]; }, $arr);
$sortedHtml = implode($arr);