0

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?

1
  • 2
    can you give a slice of array that would have the html snippets? Commented Oct 21, 2013 at 15:57

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! What if my html snippets contain php variables too? I guess I have to first compose my array then do the sorting
I found this method too on w3schools $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); ksort($age); which sounds a lot easier. What is the difference with your solution?
@Akmur This array is being sorted by keys and the keys contains names.
when you say "this" what "this" are you referring to? :) sorry not sure what you mean
@Akmur This being the array you posted in your comment there.
0

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

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.