Sort Multidimensional Array - CakePhp
Its usual that we always play around the arrays where ever we go in our daily as well as coding life.
One that hurts the sort function to be applied to those arrays that are useful for various in the team or may be next time we got stuck at some array sorting.
What I faced today is an multidimensional associative array which needed to be sort on the level 3 of the array. The solution that came up after some sort of research on the coders community that we have some functions in php that can be applied directly to sort the Multidimensional Array.
Lets use the function in CAKEPHP and make the sorting a little happy sorting.
Function Named: array_multisort click here to know more about it.
We can use this example to solve the issue:
Lets have a array name: $mainExam =
array( (int) 0 => array( 'Test' => array( 'id' => '31', 'name' => 'Maths', 'Questions' => array( (int) 0 => array( 'algebra' => '4', 'reason' => 0 ) ) ), 'student' => array( 'id' => '14', 'name' => 'inder', ) ), (int) 1 => array( 'Test' => array( 'id' => '32', 'name' => 'Maths', 'Questions' => array( (int) 0 => array( 'algebra' => '5', 'reason' => 0 ) ) ), 'student' => array( 'id' => '15', 'name' => 'shayam', ) ) );
So with the help of Set::extract in cakephp we can do it pretty straight forward as follows:
$algebraQuestions = Set::extract('/Test/Questions/algebra', $skus);Now we will have all the values of the algebra under questions array. So now we can apply array_multisort function for rest of our work here.
Like as:
array_multisort($algebraQuestions ,SORT_ASC,$mainExam);
This will sort the entire array on the basis of algebra questions although we can also use SORT_DESC for descending