简体   繁体   English

在PHP中排序HTML代码段

[英]Sorting HTML snippets in PHP

I have a need to save some html snippets to an array. 我需要将一些HTML代码段保存到数组中。 These snippets would have something like a position attribute, which I would pass as well. 这些片段将具有类似于position属性的内容,我也将通过。 I want PHP to output all of my snippets in descending order. 我希望PHP以降序输出所有代码段。

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. 我知道如何通过在数据属性中设置我的位置然后进行排序来在JS / jQuery中进行操作,但是我不确定如何在PHP中进行操作。

Any clue to point me in the right direction? 有什么线索可以指示我正确的方向吗?

Assuming your elements look like this: 假设您的元素如下所示:

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

and many of them are in another array() without any particular indexes. 并且它们中的许多都在另一个array()没有任何特定的索引。 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 参见http://php.net/manual/en/function.usort.php

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM