php - How can I group my array into groups of 3 elements, sort them by the last element and display the elements? -


i'm trying display array in groups of 3 elements, sorted last element of each group.

my array:

$info = array('goal','raul','80','foul','moneer','20','offside','ronaldo','60'); 

my expected output is:

1-foul moneer 20 2-offside ronaldo 60 3-goal raul 80 

sorted last value of element groups.

i'm using foreach display it:

$i = 0; foreach($info $key => $val) {     $i++;     echo $info[$key] . '<br>';     if ($i % 3 == 0){         echo "<br />"; } 

is possible ? , if yes, how can change code expected output?

this should work you:

first array_chunk() array chunks of 3 elements, array have structure:

array (     [0] => array         (             [0] => goal             [1] => raul             [2] => 80         )      [1] => array         (             [0] => foul             [1] => moneer             [2] => 20         )      [2] => array         (             [0] => offside             [1] => ronaldo             [2] => 60         )  ) 

after sort last value (here key 2), usort() comparing values. @ end can loop through array , display data.

<?php      $info = array('goal','raul','80','foul','moneer','20','offside','ronaldo','60');     $arr = array_chunk($info, 3);     usort($arr, function($a, $b){         if($a[2] == $b[2])             return 0;         return $a[2] > $b[2] ? 1 : -1;     });      foreach($arr $k => $v)         echo ($k+1) . "-" . implode(" ", $v) . "<br>";  ?> 

output:

1-foul moneer 20 2-offside ronaldo 60 3-goal raul 80 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -