MANnDAaR
MANnDAaR

Reputation: 2590

Position / Order div with php

I'm looking for re-ordering div position with php

My html structure is something like this

<div id="position">1,2,3,4,5</div>

    <div id="1">1</div>
    <div id="2">2</div>
    <div id="3">3</div>
    <div id="4">4</div>
    <div id="5">5</div>

Above,

'<div id="position"><php $layout ?></div>'

defines

<div id="position">1,2,3,4,5</div>

What I want is if

<div id="position">5,2,3,1,4</div>

Arrange div in relative order like this

<div id="5">5</div>
<div id="2">2</div>
<div id="3">3</div>
<div id="1">1</div>
<div id="4">4</div>

Basically I'm looking to sort as per div id in array.

Thanks

Upvotes: 0

Views: 2200

Answers (3)

Colin Fine
Colin Fine

Reputation: 3364

Your question is very unclear, because you haven't indicated how the required order is getting into your program.

But basically you have two choices (which may be combined). In either case you hold your id's in a PHP array, and either:

  • use 'usort' with a custom ordering function which gets the order from somewhere, or
  • use explicit keys in your array and sort by key using 'ksort'.#

Upvotes: 1

Steve Bergamini
Steve Bergamini

Reputation: 14600

You can do something like:

$numbers = "5,2,3,1,4";
$order = explode(',',$numbers);
foreach ($order as $i){
    echo "<div id=\"$i\">$i</div>";
}

Upvotes: 1

Shai Mishali
Shai Mishali

Reputation: 9392

PHP Doesn't actually design or format anything visual. It is just a language for processing and outputting data needed.

For your solution you might need this, but it really depends on your situation - maybe you could elaborate more?

$divs = array(1,2,3,4,5);

// Here you could reverse them by $divs = array_reverse($divs); if needed.

foreach($divs as $div)
   echo '<div id="'.$div.'">'.$div.'</div>';

If you insist on using the first div's inner content to sort the rest (I'm not sure why?) - you could use something like jQuery to do this on the client side.

Shai.

Upvotes: 0

Related Questions