0

Using php 5.3, I am trying to sort the arrays descending. I have the following multiple single arrays after a string explode:

Array
(
[0] => A
[1] => 115
[2] => 20
)
Array
(
[0] => A
[1] => 140
[2] => 50
)
Array
(
[0] => A
[1] => 120
[2] => 40
)

The output I am looking for would be to sort ascending by key[1] so it will look like this:

 Array
(
[0] => A
[1] => 115
[2] => 20
)
Array
(
[0] => A
[1] => 120
[2] => 40
)
Array
(
[0] => A
[1] => 140
[2] => 50
)

The code I have so far is :

$data = string_content_to_explode

foreach($data as $line) {

    if(substr($line,0,1)=="A") {

    $parts = explode(chr(9), $line);

// sort awards DESC
array_multisort($parts[1]);
}

echo "<pre>"; print_r($parts); echo "</pre>";

Unfortunately this has no effect whatsoever. I can not find a function or example of a foreach which can sort multiple single arrays in this way. If someone can point me in the right direction that would be great.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Renny
  • 47
  • 6
  • Did you see this http://php.net/manual/en/function.array-multisort.php already? – Norbert Jul 01 '17 at 15:07
  • Possible duplicate of [Sort Multi-dimensional Array by Value](https://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value) – mickmackusa Sep 09 '17 at 23:21

2 Answers2

0

Sort it with usort:

 usort($string_content_to_explode,function($a,$b){
     if ($a[1] == $b[1])
         return 0;
    return ($a[1] < $b[1])? -1: 1; 
 });


 var_dump($string_content_to_explode);
voodoo417
  • 11,861
  • 3
  • 36
  • 40
0

usort() is unnecessary. sort() will perform this task perfectly because you can sort on first column then second column without any hiccups.

Code: (Demo)

$data=array('A'.chr(9).'115'.chr(9).'20','B'.chr(9).'DO NOT'.chr(9).'INCLUDE','A'.chr(9).'140'.chr(9).'50','A'.chr(9).'120'.chr(9).'40');

foreach($data as $line){
    if(strpos($line,'A')!==false){  // don't use substr($line,0,1)=="A", strpos is faster/better
        $parts[]=explode(chr(9),$line); // create multi-dimensional array, instead of overwriting 1-dim array
    }
}
sort($parts);  // because first column is always "A", and you are sorting on the next column
var_export($parts);  // print to screen

Output:

array (
  0 => 
  array (
    0 => 'A',
    1 => '115',
    2 => '20',
  ),
  1 => 
  array (
    0 => 'A',
    1 => '120',
    2 => '40',
  ),
  2 => 
  array (
    0 => 'A',
    1 => '140',
    2 => '50',
  ),
)

P.S. OP originally asked for DESC order, but meant ASC order judging by expected result.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136