我需要的
阵列结构
[0] => Array
(
[type] => CACDA
[metadata] => Array
(
[0] => Array
(
[amount] => 320
[comment] =>
)
)
)
[1] => Array
(
[type] => CVMA
[metadata] => Array
(
[0] => Array
(
[amount] => 320
[comment] => Onsite After February 20
)
)
)
源代码
unset($data[0]);
//store types and the arrays the belong to
foreach($data as $k=>$v){
$type[$v['type']][]=$k;
}
//loop types, creating result array
foreach($type as $k=>$v){
$tmp=array(
'type'=>$k,
'metadata'=>array()
);
//loop all the arrays of this type
foreach($v as $w){
//store in TMP
$t=array(
'amount' => $data[$w]['amount'],
'comment' => $data[$w]['comment']
);
$t array structure
Array
(
[amount] => 320
[comment] =>
)
Array
(
[amount] => 320
[comment] => Onsite After February 20
)
Onsite After February 20Array
(
[amount] => 320
[comment] => Onsite After February 20
)
Onsite After February 20Array
(
[amount] => 370
[comment] => Onsite After February 20
)
Onsite After February 20Array
(
[amount] => 170
[comment] => Onsite After February 20
)
//sort TMP on EMPTY value
//usort($t,function ($a, $b) {
//if($a == '' && $b != '') return 1;
//if($b == '' && $a != '') return -1;
//if($b == 0){return 1;}
//return 0;
//});
arsort($t['comment']);
//store
$tmp['metadata'][]=$t;
}
$result[]=$tmp;
}
排序后数组的输出应该像ex
[1] => Array
(
[type] => CVMA
[metadata] => Array
(
[0] => Array
(
[amount] => 320
[comment] => Onsite After February 20
)
)
)
[0] => Array
(
[type] => CACDA
[metadata] => Array
(
[0] => Array
(
[amount] => 320
[comment] =>
)
)
)
我遇到的问题我也尝试过usort。
我已经尝试过使用arsort函数,但是没有任何工作可以进行排序。
请指出我做错了什么。
我应该为php中的键和值使用哪种排序功能。
您可以使用uasort
。
uasort($array, function($a) {
return ( is_null($a['metadata'][0]['comment']) OR $a['metadata'][0]['comment'] == "") ? 1 : -1;
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句