Pages

Thursday 13 June 2013

Sorting Deep Multidimentional array PHP


Given the following array:
Array 
(
[0] => Array
(
[0] => Array
(
[key1] => var1
[key2] => var2
[sortOnMe] => 4
)

[1] => N/A
[2] => N/A
[3] => N/A
)

[1] => Array
(
[0] => Array
(
[key1] => var1
[key2] => var2
[sortOnMe] => 2
)

[1] => N/A
[2] => N/A
[3] => N/A
)
)
Given the following array:
Array 
(
[0] => Array
(
[0] => Array
(
[key1] => var1
[key2] => var2
[sortOnMe] => 4
)

[1] => N/A
[2] => N/A
[3] => N/A
)

[1] => Array
(
[0] => Array
(
[key1] => var1
[key2] => var2
[sortOnMe] => 2
)

[1] => N/A
[2] => N/A
[3] => N/A
)
)
How can I sort this array considering the key I want is deep in the structure?
I assume usort but not sure what to pass into the function?
 

Ans:

usort($arr, "mysortfunc");

function mysortfunc($a, $b)
{
if ($a[0]['sortOnMe'] == $b[0]['sortOnMe'])
{
return 0;
}
else
{
return ($a[0]['sortOnMe'] < $b[0]['sortOnMe']) ? -1 : 1;
}
}

 

No comments:

Post a Comment