Reputation: 306
How to sort following array in descending order by sorder
? The whole array is considered to be one array for descending sorting.I see some other questions like this but none of them helped me.
Array
(
[0] => Array
(
[0] => Array
(
[id] => 2208
[status] => u13333333333333
[user_id] => 6
[sorder] => 3
)
[1] => Array
(
[id] => 2208
[status] => user111111111111111
[user_id] => 6
[sorder] => 1
)
)
[1] => Array
(
[0] => Array
(
[id] => 2209
[status] => u222222222222222222222
[user_id] => 5
[sorder] => 2
)
)
)
Edit May be this is another form of the array in two dimensional.
Array
(
[userPosts] => Array
(
[0] => Array
(
[0] => Array
(
[id] => 2208
[status] => u13333333333333
[user_id] => 2208
[sorder] => 3
)
[1] => Array
(
[id] => 2208
[status] => user111111111111111
[user_id] => 2208
[sorder] => 1
)
)
[1] => Array
(
[0] => Array
(
[id] => 2209
[status] => u222222222222222222222
[user_id] => 2209
[sorder] => 2
)
)
)
)
Upvotes: 0
Views: 703
Reputation: 1391
$yourArray = array(
array(
array('id' => 2208,
'status' => 'u13333333333333',
'user_id' => 6,
'sorder'=>3
),
array('id' => 2208,
'status' => 'user111111111111111',
'user_id' => 6,
'sorder'=>1
),
),
array(
array('id' => 2209,
'status' => 'u222222222222222222222',
'user_id' => 5,
'sorder'=>2
),
),
);
/*Merger arrays as one */
function loopArrayMerger(array $bigArray) {
if (!$bigArray) {
return array();
}
return call_user_func_array('array_merge', $bigArray);
}
$flatedArray = loopArrayMerger($yourArray);
/*Call back function for sorting, if you want in ascending order just replace 1:-1 with -1:1*/
function compareElementsInArray($a, $b) {
if ($a['sorder'] == $b['sorder']) {
return 0;
}
return ($a['sorder'] < $b['sorder']) ? 1 : -1;
}
/*Finally sort your array*/
uasort($flatedArray, 'compareElementsInArray');
echo '<pre>';
print_r($flatedArray);
Upvotes: 3
Reputation: 24406
Do you want to maintain your two main arrays or merge them into one? Here's a solution for combining into one with something like this:
<?php
// merge branches of array
$array = array_merge($yourarray[0], $yourarray[1]);
$sorders = array();
foreach($array as $key => $current) {
foreach($current as $subkey => $value) {
// create new array with sorder as key, original key as value
$sorders[$value['sorder']] = $subkey;
}
}
// sort by key (sorder)
ksort($sorders);
// create new array with ordered results
$new_array = array();
foreach($sorders as $sorder => $subkey) {
// add values back
$new_array[] = $array[0][$subkey];
}
print_r($new_array);
?>
Another question is how is this array being created initially? You may find that whatever is producing it (if it's a framework of some sort) might give you the option when retrieving the data to order by that field. If you're getting it with your own query from say MySQL, might be better to order by that field in your SQL query instead of doing it after...?
Upvotes: 0