I'm trying to display my array in groups of 3 elements, sorted by the 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 by the last value of the element groups.
I'm using foreach to display it:
$i = 0;
foreach($info as $key => $val) {
$i++;
echo $info[$key] . '<br>';
if ($i % 3 == 0){
echo "<br />";
}
Is this possible ? And if yes, how can I change my code to get my expected output?
This should work for you:
First we array_chunk()
your array into chunks of 3 elements, so your array will have this 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 this we sort it by the last value (here key 2), with usort()
by simply comparing the values. Then at the end you can just loop through your array and display the 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 as $k => $v)
echo ($k+1) . "-" . implode(" ", $v) . "<br>";
?>
output:
1-foul moneer 20
2-offside ronaldo 60
3-goal raul 80