Forum Moderators: coopster

Message Too Old, No Replies

Sorting multidimensional array

         

usrbin

12:49 am on Dec 23, 2016 (gmt 0)

5+ Year Member Top Contributors Of The Month



I have a string made up of different parts that I need to reorder:

$string = 'coke:brown:120;water:clear:0;milk:white:90';

The string comprises of fields separated by a semicolon, with sub-parts separated by a colon.

I'm trying to explode the string into a multidimensional array sorted by the value in the third sub-part.

I have:

$new = array();
$temp = explode(';', $string);
foreach($temp as &$subpart) $new[] = explode(':', $subpart);

Its not very elegant, but it gets the data into a multidimensional array, but I just don't know how to sort it. Any tips?

coopster

4:35 pm on Jan 3, 2017 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



A quick search over the WebmasterWorld forums here turns up some examples:

Help sorting a multidimensional array [webmasterworld.com]
multisort unknown N levels multidimensional array [webmasterworld.com]

phparion

5:06 pm on Jan 9, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I do not understand why are you using by-reference in foreach loop. Anyway, you can use usort() function to send all the values of your array to a custom function that will sort it. See the following,

$string = 'coke:brown:120;water:clear:0;milk:white:90';
$new = array();
$temp = explode(';', $string);
foreach($temp as $subpart) $new[] = explode(':', $subpart);
echo "<pre>";
print_r($new);
function sortIT($a,$b){
return $a[2] - $b[2];
}
usort($new, "sortIT");
print_r($new);


here is the working demo [fastcreators.com ]