dsfdgdsfd23212 2015-11-30 10:29
浏览 35
已采纳

根据组为值分配键

Values of array are grouped together if they have the same $record->parent_id. How can I assign to each group a key that starts from 0 and iterates for every member of a group and only for that specific group? Every consecutive new group starts from 0 again.

Example: if $record->parent_id is 2, current iteration of foreach loop assigns a 0 to key. Next iteration has $record->parent_id of value 56, its key is 0 again! Next iteration has $record->parent_id of value 2 again, hence its key is now 1 and so forth.

My current code:

<?php foreach ($records as $key => $record): ?>   

<tr id="<?php echo $key; ?>">
    <td><?php echo $record->parent_id; ?></td>
    <td><?php echo $key; ?></td> //here I wish to get key starting from 0
    <td><?php echo $record->title; ?></td>
</tr>     

<?php endforeach; ?>
  • 写回答

1条回答 默认 最新

  • douli1854 2015-12-02 10:22
    关注

    First of all I notice that your current code introduces an ambiguity, since it uses $key twice for different things.

    If I correctly understand what's your need:

    • $key in 1st and 2nd lines is some existing key you get from each record and which must become the id of the corresponding generated <tr>.
      To emphasize it I will change its name below to $record_key
    • $key in ghe 4th line is a count number within the group of all records having the same parent_id.
      This can be achieved by merely counting rows in their relevant group.

    Here is the result:

    foreach ($records as $record_key => $record) {
      if (!isset($groups[$record->parent_id]) {
        $groups[$record->parent_id] = 0;
      }
    ?>   
    <tr id="<?php echo $record_key; ?>">
        <td><?php echo $record->parent_id; ?></td>
        <td><?php echo $groups[$record->parent_id]++; ?></td>
        <td><?php echo $record->title; ?></td>
    </tr>     
    <?php
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?