0

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>
6
  • Hi, please check this topic: stackoverflow.com/questions/17017148/…. Of course, this is via javascript :) Commented Oct 29, 2016 at 19:58
  • @GeorgesO. It needs to be in php Commented Oct 29, 2016 at 20:00
  • Ok. So, you need to do it before rendering the page :) Commented Oct 29, 2016 at 20:00
  • 1
    Hi Scriptim, you should make your question more clearly. Please paste your php code here. Commented Oct 29, 2016 at 20:01
  • @phper What do you mean? Commented Oct 29, 2016 at 20:01

2 Answers 2

0

If you can't do it with javascript ... order before rendering the page. Example with a kind of MVC:

  1. Masterdata
  2. Rendering

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.