gpt4 book ai didi

php - 按数字对奇怪的数组进行排序

转载 作者:行者123 更新时间:2023-12-04 13:44:19 25 4
gpt4 key购买 nike

这是我的数组:

$hello = Array(
[text] => Array([name] => blabla [num] => 10)
[sometext] => Array([name] => blabla [num] => 2)
[anytext] => Array([name] => blabla [num] => 1)
)

如何按[num]对这个数组进行排序?

应该看起来像(回显):

<ul>
<li>anytext</li>
<li>sometext</li>
<li>text</li>
</ul>

谢谢。

最佳答案

使用uasort() :

<?php
$hello = array(
'text' => array('name' => 'blabla', 'num' => 10),
'sometext' => array('name' => 'blabla', 'num' => 2),
'anytext' => array('name' => 'blabla', 'num' => 1)
);

function sort_func($x, $y) { // our custom sorting function
if($x['num'] == $y['num'])
return 0; // zero return value means that the two are equal
else if($x['num'] < $y['num'])
return -1; // negative return value means that $x is less than $y
else
return 1; // positive return value means that $x is more than $y
}

uasort($hello, 'sort_func');

echo '<ul>';
foreach($hello as $key => $value)
{
echo '<li>'.htmlspecialchars($key).'</li>';
}
echo '</ul>';

关于php - 按数字对奇怪的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3621253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com