简体   繁体   中英

grouping elements for same object

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:

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

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
        
     )

A simple check in the loop like below will identify that the current occurance is for the same person as the last occurance.

$id_person = null;
foreach($results as $result){
    if ( $id_person == $result->id_person ) {
        echo'<td>&nbsp;</td><td>'.$result->id_class.'</td>';`  
    } else {
        echo'<td>'.$result->id_person.'</td><td>'.$result->id_class.'</td>';`   
        $id_person = $result->id_person;
    }
}

This should produce a table like this.

1   32
5   32
7   9
    40

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:

//$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
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM