akmur
akmur

Reputation: 1635

Sorting HTML snippets in PHP

I have a need to save some html snippets to an array. These snippets would have something like a position attribute, which I would pass as well. I want PHP to output all of my snippets in descending order.

I know how to do it in JS/jQuery, by setting my position in a data attribute and then sorting, but I'm unsure how to proceed in PHP.

Any clue to point me in the right direction?

Upvotes: 0

Views: 72

Answers (2)

Richard Poole
Richard Poole

Reputation: 591

Assuming you could populate the array in many place, and in no particular order.

$htmlSnippets = new Array();
$htmlSnippets[1] = "<secondsnippet>";
$htmlSnippets[0] = "<firstsnippet>";
$htmlSnippets[2] = "<thirdsnippet>";

ksort($htmlSnippets);
foreach( $htmlSnippets as $snippet ){
    echo $snippet;
}

Upvotes: 0

Cobra_Fast
Cobra_Fast

Reputation: 16101

Assuming your elements look like this:

array(
    'snippet' => '...html...',
    'position' => 0..n
);

and many of them are in another array() without any particular indexes. Then you could do:

$array = ...; // as described above
usort(
    &$array,
    function ($a, $b)
    {
        if ($a['position'] == $b['position'])
            return 0;
        return ($a['position'] < $b['position'] ? -1 : 1);
    }
);

See http://php.net/manual/en/function.usort.php

Upvotes: 1

Related Questions