我有一系列供应商叫做:
$listOfVendors
我在视图中使用foreach遍历此数组。
<?php foreach($listOfVendors as $vendor):?>
<p class="vendor">
<span class="vendor-title"><?php echo $vendor->name ?>(<?php echo $vendor->country ?>)</span>,
<?php echo $vendor->goods ?>, <a href="<?php echo $vendor->site_adres ?>" class="vendor-link"><?php echo $vendor->site_adres ?></a>
</p>
<?php endforeach ?>
每个供应商对象都具有以下属性:
供应商_Id ,名称,国家,商品, site_address , activities_Id 即可。活动_Id的最后一个是表活动的FK,目前有两种类型的活动:经销商和艺术家。
现在我想为每种类型的供应商添加一个标头。所以想得到类似的东西:
艺术家
Vendor1(DE),Eigen posters e.a.商品,http://www.linktosite.com
经销商
Vendor2(BE),Toys,DVD,书籍,http://www.anotherlink.be
Vendor3(FR),商品,http://www.anotherlink2link.be
我该怎么做? 我似乎无法理解这个看似简单的事情。
//Get the vendor information and add the needed headers
//Here I get all the vendors
if($listOfVendors = $this->atsusacon_model->get_records()) {
foreach($listOfVendors as $vendor) {
$listOfVendorsByType[$vendor->activities_Id][] = $vendor;
}
$data['listOfVendorsByType'] = $listOfVendorsByType;
var_dump($listOfVendorsByType);
}
<section class="vendors-overview twelvecol clearBoth">
<?php foreach($listOfVendorsByType as $activity):?>
<?php if ($activity[0]->activities_Id == 1) :?>
<h3>Artists</h3>
<?php else :?>
<h3>Dealers</h3>
<?php endif ?>
<?php foreach($activity as $vendor):?>
<p class="vendor">
<span class="vendor-title"><?php echo $vendor->name ?>(<?php echo $vendor->country ?>)</span>, <?php echo $vendor->goods ?>, <a href="<?php echo $vendor->site_address ?>" class="vendor-link"><?php echo $vendor->site_address ?></a>
</p>
<?php endforeach ?>
<?php endforeach ?>
</section>
我可以让它变得更有活力,但就目前而言,这正是应该如此。
$ listOfVendorsByType的var_dump如下所示:
答案 0 :(得分:1)
猜猜您必须获取外键的数据,而不是必须循环两次: 确保你&#34;链接&#34;供应商和活动正确。
foreach (activities ...) {
// looping 2 times
foreach (vendor ...) {
// looping x times (=amount of vendors)
...
}
}
答案 1 :(得分:1)
您必须创建一个嵌套数组:
<?php
foreach($listOfVendors as $vendor) {
$vendorsByType[$vendor['activities_id']][] = $vendor;
}
?>
现在你必须使用两个foreach循环遍历这个嵌套数组。
答案 2 :(得分:1)
添加此数组
$header = array( "header1", "header2", "header3" );
// now $ header [0] =“header1”$ header [1] =“header2”等等
$i=0;
<?php foreach($listOfVendors as $vendor):?>
<p class="header">
<?php echo $header[$i]; $i++; ?>
</p>
<p class="vendor">
<span class="vendor-title"><?php echo $vendor->name ?>(<?php echo $vendor->country ?>)</span>,
<?php echo $vendor->goods ?>, <a href="<?php echo $vendor->site_adres ?>" class="vendor-link"><?php echo $vendor->site_adres ?></a>
</p>
<?php endforeach ?>