0

I have a multilevel array as below

array( 
    (int)0=>array(
              'User' => array(
        'PostType' => array(
            'PHP' => array(
                'id' => '2',
                'type_title' => 'Core Questions',
                'type_description' => 'none',
                'type_sort_order' => '7'
                'Post'=>array(
                    ......
                    ),
            ),
            'ASP' => array(
                'id' => '1',
                'type_title' => 'Core Questions',
                'type_description' => 'none',
                'type_sort_order' => '1'
                'Post'=>array(
                    ......
                    ),
            ),
        ),
)));

I have fetched a user with its post categorized by postType
postType has type_sort_order field
I want to sort sub array PostType by type_sort_order field
so that ASP come before PHP
I tried usort as below

usort($arr,function(){
                return  ($a[0]['User']['PostType']['post_sort_order'] < $b[0]['User']['PostType']['post_sort_order'])?1:-1;
            });

and also many other sort but not getting correct result

1
  • You need to set the array as $a[0] and sort on that if you want correct results. Then you can just minus value b from value a and it should sort it no problem. If it doesn't sort in the right order try minusing value a from value b. Commented Mar 19, 2015 at 8:47

2 Answers 2

1

array_multisort will work. Solution as follows:

$list = //Your array

$sortOrders = array();
foreach ($list[0]['User']['PostType'] as $postType) {
    $sortOrders[] = $postType['type_sort_order'];
}

array_multisort($sortOrders, $list[0]['User']['PostType']);

This will grab all the sort orders in an array ordered the same as your starting array. Using array_multisort on both arrays will sort the first array, and also apply that new order to the second array, giving you the result you're after.

Sign up to request clarification or add additional context in comments.

Comments

0

Your looking for http://php.net/manual/en/function.array-multisort.php

Loop though PostType and take all type_sort_order and place in a seperate array. then use that array as an argument for array_multi_sort

it seems you are just trying to sort the sub array PostType so just pass that array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.