我需要将一些 html 片段保存到数组中。这些片段会有类似位置属性的东西,我也会传递。我希望 PHP 以降序输出我的所有片段。
我知道如何在 JS/jQuery 中做到这一点,通过在数据属性中设置我的位置然后排序,但我不确定如何在 PHP 中进行。
有什么线索可以指出我正确的方向吗?
假设您的元素如下所示:
array(
'snippet' => '...html...',
'position' => 0..n
);
其中许多在另一个array()
没有任何特定索引的情况下。然后你可以这样做:
$array = ...; // as described above
usort(
&$array,
function ($a, $b)
{
if ($a['position'] == $b['position'])
return 0;
return ($a['position'] < $b['position'] ? -1 : 1);
}
);
假设您可以在许多地方填充数组,并且没有特定的顺序。
$htmlSnippets = new Array();
$htmlSnippets[1] = "<secondsnippet>";
$htmlSnippets[0] = "<firstsnippet>";
$htmlSnippets[2] = "<thirdsnippet>";
ksort($htmlSnippets);
foreach( $htmlSnippets as $snippet ){
echo $snippet;
}