简体   繁体   中英

How to iterate data and display as per their belonging group name in php

I am selecting data from database and displaying in table but now i want to display all data as per their agent name and balance amt of their agent which is associated on other table.

Customer Table

    id agent_id
    1    5
    2    5
    3    6

    Balance table

    id agent_id bal_amt
    1    5       25000
    2    6       7000

But i want to display like below format, means i want to display agent name in row and rest data related with agent name in columns

Expected result

Agentname  category  subcategory  balance
ABC                               25000
            Ring     plastic
            Node     fibre
            test     rassi
XYZ                              7000
            sofa     rod
            mate     code

Below is my code

     <?php  
                            $finalArray = [];
                            foreach ($customerlist as $user) { print_r($user);exit;
                                $finalArray[$user['agent']['name']][] = $user;
                            }
                            foreach ($finalArray as $key => $value) {
                        ?>

    <tr>
                            <td colspan="7"><?php echo $key; ?></td>
                            <td colspan="2">25000</td>
                        </tr> 
                        <?php foreach ($value as $user) { ?>
                         <tr>
                        <td>&nbsp;</td> 
                        <td><?php echo $user['product']['name'];  ?></td>
<?php }} ?>

To achieve this, need to first group all entries for agents in one array and then traverse through those to get desired output. Try this code:

<?php
$finalArray = [];
foreach ($customerlist as $user) {
    $finalArray[$user['agent']['name']][] = $user;
}

foreach ($finalArray as $key => $value) {
    ?>
    <tr>
        <td><?php echo $key; ?></td> 
        <td>&nbsp;</td>
        <td>&nbsp;</td>
    </tr>  
    <?php foreach ($value as $user) { ?>
        <tr>
            <td>&nbsp;</td> 
            <td><?php echo $user['product']['name']; ?></td>
            <td><?php echo $user['subproduct']['name']; ?></td>
        </tr>  
        <?php
    }
}
?>

Here first tr will be print Agent Name and other tr in inner foreach loop will print to entries of that agent.

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