PHP数组按描述顺序进行排序
我的代码在这里:我尝试使用排序函数,但没有成功。这是我的工作数组代码: 我的代码显示输出未排序顺序:PHP数组按描述顺序进行排序,php,arrays,sorting,Php,Arrays,Sorting,我的代码在这里:我尝试使用排序函数,但没有成功。这是我的工作数组代码: 我的代码显示输出未排序顺序: <?php foreach($aCities as $key=>$val) { foreach($diskspace[$val] as $key=>$val2) { if(isset($val2['data'])) { //'MBytes %.f'=155.000000%;
<?php
foreach($aCities as $key=>$val)
{
foreach($diskspace[$val] as $key=>$val2)
{
if(isset($val2['data']))
{
//'MBytes %.f'=155.000000%;
preg_match("/'(.*?)ytes \%.f'=(.*?)\%;/",$val2['data'],$aVal);
echo($val.' '.ceil($aVal[2]).' '.$aVal[1].'<br />');
}
}
}
?>
我需要以DESC(MemorySize)顺序输出,如:
I 10 MB
T 6 MB
S 3 MB
也许你可以试着用一下 编辑 例如,如果您有一个数字数组
$number\u array=[1,2,3,4]
,并且您使用函数rsort():rsort($number\u array)
生成的数组将按该顺序具有值[5,4,3,2,1]
然而,对于您的示例,从代码来看,使用
您也可以将其用作闭包
usort($diskspace,function($a,$b){return$b[0]['data']-$a[0]['data'];}
我会尝试上面的方法。如果不亲自测试它,它会返回一个数组,就像您按数据从高到低排序的数组一样。the[0]
将有效地比较每个数组的第一个元素的数据属性,这应该不是问题,因为构成$aCities
的每个数组只有一个元素。$out=array();
$out = array();
foreach($diskspace as $key => $value) // parse original array
{
$row = array_values($value);
$row = $row[0];
preg_match('/=(\d+)\./', $row['data'], $match); // get numerical value
// MB as you did not show what else can be
$out[] = array($key, $match[1] + 0, 'MB'); // convert $match[1] to integer
}
uasort($out, function ($a, $b) { // sort by the second column
return $a[1] < $b[1] ? 1 : -1;
});
foreach($out as $row) // output sorted data
echo join(' ', $row) . "\n";
foreach($key=>$value的磁盘空间)//解析原始数组
{
$row=数组_值($value);
$row=$row[0];
preg_match('/=(\d+)\./',$row['data'],$match);//获取数值
//MB,因为您没有显示其他内容
$out[]=数组($key,$match[1]+0,'MB');//将$match[1]转换为整数
}
uasort($out,函数($a,$b){//按第二列排序
返回$a[1]<$b[1]?1:-1;
});
foreach($out as$row)//输出排序数据
回显联接(“”,$row)。“\n”;
噢,我觉得您已经在使用sort()函数了。我将更新我的答案。rsort()在整数值的情况下从最高到最低排序。答案更新为使用usort(),这将由用户定义的函数进行排序。
$out = array();
foreach($diskspace as $key => $value) // parse original array
{
$row = array_values($value);
$row = $row[0];
preg_match('/=(\d+)\./', $row['data'], $match); // get numerical value
// MB as you did not show what else can be
$out[] = array($key, $match[1] + 0, 'MB'); // convert $match[1] to integer
}
uasort($out, function ($a, $b) { // sort by the second column
return $a[1] < $b[1] ? 1 : -1;
});
foreach($out as $row) // output sorted data
echo join(' ', $row) . "\n";
usort($diskspace, function($a, $b) {
$a = reset($a); $b = reset($b);
$aVal = filter_var($a['data'], FILTER_SANITIZE_NUMBER_INT);
$bVal = filter_var($b['data'], FILTER_SANITIZE_NUMBER_INT);
if ($aVal == $bVal) {
return 0;
}
else if ($aVal > $bVal) {
return -1;
}
else {
return 1;
}
});
var_dump($diskspace);