this is a simplified array of objects with different elements( it’s a result from database). I’m trying to group classes together for each person so I can show it in an html table as final result, I’m using this after foreach loop:
JavaScript
x
echo'<td>'.$result->id_person.'</td>';
echo'<td>'.$result->id_class.'</td>';`
I have tried parsing the Array with 2 for loops and if loop, but it didn’t work as expected. Please can anyone help me with that?
I would like to group id_class
for same person
JavaScript
Array
(
[0] => stdClass Object
(
[id_person] => 1
[id_class] => 32
)
[1] => stdClass Object
(
[id_person] => 5
[id_class] => 32
)
[2] => stdClass Object
(
[id_person] => 7
[id_class] => 9
)
[3] => stdClass Object
(
[id_person] => 7
[id_class] => 40
)
Advertisement
Answer
With the hint of RiggsFolly, I used also $previous to save the previous element in the current iteration and compare if it’s the same, so this is working:
JavaScript
//$res is an array of objects that I'm parsing
$id_person= null;
$tab = [];
$previous = [];
$len = count($res);
for($i = 0, $i<$len, $i++){
if($id_person== $res[$i]->id_person){
array_push($tab, ($res[$i]->id_class));
}else{
array_push($previous, $res[$i]->id_person);
echo'<tr><td >'.$res[(i-1)]->id_person.'</td><td >'.foreach($tab as $drawTab){ echo $drawTab; }.'</td></tr>';
$tab = array();
$tab = $res[$i]->id_class;
}
// check when it's the last element of the array :
if($i == ($len-1)){ ?>
<tr><td> <?php foreach($previous as $pre){echo $pre; } ?> </td>
<td> <?php foreach($array as $arr){echo $arr.'<br/>'; } ?> </td></tr>
<?php
}
}