问题
I am reading mysql fine to pull a set of data given a particular ID, this returns an array to my script. Thats the easy bit. Example of which is here an is stored in an array called $history
Array ( [serviceID] => 1 [VesselTag] => 1000001 [component] => Engine 1 [item] => Caterpillar [serial] => 123456 [comment] => Something in here like this [parts] => Oil [lat] => 50.38313740 [longitude] => -4.03461360 [engineer] => 27 [date] => 2019-05-30 19:25:56 )
Array ( [serviceID] => 2 [VesselTag] => 1000001 [component] => Engine 2 [item] => Caterpillar [serial] => 677889 [comment] => Did a full overhaul of top section replaced everything [parts] => everything [lat] => 50.38309180 [longitude] => -4.03468820 [engineer] => 27 [date] => 2019-05-30 19:27:29 )
Array ( [serviceID] => 3 [VesselTag] => 1000001 [component] => Engine 1 [item] => Caterpillar [serial] => 123456 [comment] => This seems quite usable [parts] => Oil [lat] => 50.38345892 [longitude] => -4.03475649 [engineer] => 27 [date] => 2019-05-30 19:29:23 )
What I would like to do is now generate an accordion 'card-body' grouping the cards based on [component]s from the list. Sometime the array may have more or less, so there is going to be anywhere from 0 to 7 cards [components] showing.
<div class="card">
<div class="card-header">
<a class="card-link" data-toggle="collapse" href="#collapseOne">
$array[Component] **<--- Guessing this would be from a ```foreach``` or ```while``` loop???**
</a>
</div>
<div id="collapseOne" class="collapse" data-parent="#accordion">
<div class="card-body">
<?php **THIS IS WHERE I WILL DISPLAY THE ROWS OF DATA ASSOCIATED TO THE [component] IN QUESTION ?>**
</div>
</div>
</div>
I am just really struggling getting my head around which loop to use, and to be able to drive it by the [components].
Its doing my head in......
回答1:
After quite some time looking at different articles I seem to have come up with something that works..... I think it is relatively efficient, but happy for someone to tell me otherwise....
<div id="accordion">
<?php $newArray=array();
foreach($history as $val){
$key=$val['component'];
$grouped[$key][]=$val;
}
foreach($grouped as $group){?>
<div class="card">
<div class="card-header">
<a class="card-link" data-toggle="collapse" href="#<?php echo str_replace(' ', '',$group[0]['component']); ?>">
<?php echo $group[0]['component']; ?>
</a>
</div>
<div id="<?php echo str_replace(' ', '',$group[0]['component']); ?>" class="collapse" data-parent="#accordion">
<div class="card-body">
<?php foreach ($group as $occurance){
echo $occurance['date'] . ' - ' . $occurance['comment'] . ' - ' . $occurance['parts'] . ' - ' . $occurance['engineer'];
echo '<br>';
} ?>
</div>
</div>
</div>
<?php }?>
</div>
来源:https://stackoverflow.com/questions/56395502/dynamically-generate-an-accordion-based-on-array-data