What I need
Array Structure
[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
)
)
)
source code
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;
}
output of array after sorting Should come Like 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] =>
)
)
)
problem i having i have also tried with usort .
i have tried with arsort function but nothing is working for sorting .
please suggest where i have done wrong .
which sorting function i should use for key & value in php.
PHP - Sort Functions For Arrays sort() - sort arrays in ascending order. rsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key.
You can use uasort
.
uasort($array, function($a) {
return ( is_null($a['metadata'][0]['comment']) OR $a['metadata'][0]['comment'] == "") ? 1 : -1;
});
https://eval.in/207091
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With