Advanced sorting of a multidimensional array in PHP -
i have looked through answers sorting multidimensional arrays in php on stack overflow, none have straight answered question.
from various answers have understood should using either php usort
function or php array_multisort
function, not sure how apply these specific array structure:
here variable $array
:
array ( [0] => array ( [field1] => 10 [field2] => 100 [field3] => 100 [subarray] => array ( [0] => array ( [field1] => 10 [field2] => 100 [field3] => 100 ) [1] => array ( [field1] => 10 [field2] => 100 [field3] => abcorderbythis ) ) ) [1] => array ( [field1] => 10 [field2] => 100 [field3] => 100 [subarray] => array ( [0] => array ( [field1] => 10 [field2] => 100 [field3] => 100 ) [1] => array ( [field1] => 10 [field2] => 100 [field3] => ghiorderbythis ) ) ) [2] => array ( [field1] => 10 [field2] => 100 [field3] => 100 [subarray] => array ( [0] => array ( [field1] => 10 [field2] => 100 [field3] => 100 ) [1] => array ( [field1] => 10 [field2] => 100 [field3] => deforderbythis ) ) ) )
i able sort array field3
of last array in subarray
. accessing element easy plenty php end
function so:
<?php foreach($array $array_single){ foreach(end($array_single['subarray']) $sub_array){ echo $sub_array; } } ?>
and on i'm stuck in how sort multidimensional array alphabetically next result:
$array[0]
- remains on top because field3
value abcorderbythis
$array[2]
- jumps middle because field3
value deforderbythis
$array[1]
- @ bottom because field3
value ghiorderbythis
thanks in advance!
try code:
$array = array(); $arraytemp['field1'] = 10; $arraytemp['field2'] = 100; $arraytemp['field3'] = 100; $arraytemp['subarray'][0]["field1"] = 10; $arraytemp['subarray'][0]["field2"] = 100; $arraytemp['subarray'][0]["field3"] = 100; $arraytemp['subarray'][1]["field1"] = 10; $arraytemp['subarray'][1]["field2"] = 100; $arraytemp['subarray'][1]["field3"] = "abcorderbythis"; $array[] = $arraytemp; $arraytemp['field1'] = 10; $arraytemp['field2'] = 100; $arraytemp['field3'] = 100; $arraytemp['subarray'][0]["field1"] = 10; $arraytemp['subarray'][0]["field2"] = 100; $arraytemp['subarray'][0]["field3"] = 100; $arraytemp['subarray'][1]["field1"] = 10; $arraytemp['subarray'][1]["field2"] = 100; $arraytemp['subarray'][1]["field3"] = "ghiorderbythis"; $array[] = $arraytemp; $arraytemp['field1'] = 10; $arraytemp['field2'] = 100; $arraytemp['field3'] = 100; $arraytemp['subarray'][0]["field1"] = 10; $arraytemp['subarray'][0]["field2"] = 100; $arraytemp['subarray'][0]["field3"] = 100; $arraytemp['subarray'][1]["field1"] = 10; $arraytemp['subarray'][1]["field2"] = 100; $arraytemp['subarray'][1]["field3"] = "deforderbythis"; $array[] = $arraytemp; // sort multidimensional array usort($array, "custom_sort"); // define custom sort function used in usort function custom_sort($a,$b) { homecoming strcmp($a['subarray'][1]["field3"], $b['subarray'][1]["field3"]); }
php multidimensional-array
No comments:
Post a Comment