我如何组织php foreach?我已经尝试了5天,但仍然无法使其工作 我不知道php foreach它是如何工作的,但我正在学习它, 感谢大家的建议
原始php:
<?php if(isset($this->leading) && count($this->leading)): ?>
<?php foreach($this->leading as $key=>$item): ?>
<?php
$this->item=$item;
echo $this->loadTemplate('item');
?>
<?php endforeach; ?>
<?php endif; ?>
<?php if(isset($this->primary) && count($this->primary)): ?>
<?php foreach($this->primary as $key=>$item): ?>
<?php
$this->item=$item;
echo $this->loadTemplate('item');
?>
<?php endforeach; ?>
<?php endif; ?>
<?php if(isset($this->secondary) && count($this->secondary)): ?>
<?php foreach($this->secondary as $key=>$item): ?>
<?php
$this->item=$item;
echo $this->loadTemplate('item');
?>
<?php endforeach; ?>
<?php endif; ?>
我试过
<?php if(isset($this->leading) && count($this->leading)) && (isset($this->primary) && count($this->primary)) && (isset($this->secondary) && count($this->secondary)): ?>
<!-- Leading items -->
<?php foreach (array($this->leading, $this->primary, $this->secondary) as $key=>$item) ($this->leading as $key=>$item): ?>
<?php
// Load category_item.php by default
$this->item=$item;
echo $this->loadTemplate('item');
?>
<?php endforeach; ?>
<?php endif; ?>
但没有工作
一如既往,感谢您的协助!
谢谢!每个人:)
谢谢,史蒂芬!
答案 0 :(得分:1)
你的意思是这样的......?
<?php
$arr = array();
$arr[] = $this->leading;
$arr[] = $this->primary;
$arr[] = $this->secondary;
foreach($arr as $v) {
if(is_array($v) && (count($v) > 0)) {
foreach($v as $item) {
$this->item=$item;
echo $this->loadTemplate('item');
}
}
}
?>
答案 1 :(得分:0)
定义如下函数:
function foobar ($tmp) {
if(isset($tmp) && count($tmp)) {
foreach ($tmp as $key => $item) {
// Load category_item.php by default
$this->item = $item;
echo $this->loadTemplate('item');
}
}
}
并使用您的数据调用它:
foobar($this->leading);
foobar($this->primary);
foobar($this->secondary);
答案 2 :(得分:0)
处理此问题的最简单方法是首先构建一个包含所需项目的列表,然后只使用一个foreach循环遍历该列表。
我还建议在是否定义三个变量(前导,主要,次要)方面有所建议。如果你可以保证它们已被设置并且是数组 - 即使它们是空数组,它也可以使你的代码变得如此简单:
<?php
$items = array_merge($this->leading, $this->primary, $this->secondary);
foreach ($items as $Item) {
$this->item = $item;
$this->loadTemplate('item');
}
?>
如果您真的不知道变量是否已设置,并且您无法在其他位置重构代码以进行更改,则可以执行以下操作:
<?php
$items = array();
if (isset($this->leading)) $items = array_merge($items, $this->leading);
if (isset($this->primary)) $items = array_merge($items, $this->primary);
if (isset($this->secondary)) $items = array_merge($items, $this->secondary);
foreach ($items as $Item) {
$this->item = $item;
$this->loadTemplate('item');
}
?>