[英]looping through array in cakephp still has Undefined offset
I'm using cakephp 2.2.5 for this. 我正在使用cakephp 2.2.5。
I've got a contained find in one controller that pulls a list of four news items from a 'has many' relationship. 我在一个控制器中有一个包含的查找,它从“有很多”关系中提取了四个新闻列表。
I'm trying to produce a list of these four items, but can't seem to get the php foreach loop working. 我正在尝试生成这四个项目的列表,但似乎无法让php foreach循环工作。
the controller array is this: 控制器数组是这样的:
$newsLists = $this->Industry->find('all', array(
'conditions' => array('id' => $id),
'fields' => array('id'),
'contain' => array(
'News' => array(
'conditions' => array('News.type' => 'main','News.active' => 'Yes'),
'fields' => array(
'News.type',
'News.id',
),
'order' => array(
'News.created' => 'desc',
),
'limit' => 3
))));
$this->set('newsLists', $newsLists);
The debug output works fine: 调试输出工作正常:
Array
(
[0] => Array
(
[Industry] => Array
(
[id] => 1
[tags] =>
)
[News] => Array
(
[0] => Array
(
[type] => main
[id] => 10
[industry_id] => 1
)
[1] => Array
(
[type] => main
[id] => 11
[industry_id] => 1
)
[2] => Array
(
[type] => main
[id] => 12
[industry_id] => 1
)
)
)
) )
but this foreach loop only display one item: 但是这个foreach循环只显示一个项目:
<ul>
<?php
$i = 0;
foreach ($newsLists as $newsList): ?>
<li><?php echo $newsList['News'][$i]['slug']; ?></li>
<?php endforeach; ?>
thanks 谢谢
It should be - 它应该是 -
<?php foreach ($newsLists['News'] as $newsList): ?>
<li><?php echo $newsList['field to print']; ?></li>
<?php endforeach; ?>
Some points you should take care off - 你应该注意的一些要点 -
There is no slug field.
You have mentioned fields - type & id. But the industry_id is also fetched.
You have there two problems: 你有两个问题:
you echo
es an entry using $i
but never increment this value, $i
is still 0. And there is only one-step loop, you loop over the array with only one record. 你使用$i
echo
一个条目但是从不递增这个值, $i
仍然是0.而且只有一步循环,你只用一条记录循环数组。
slug
isn't defied in your array, only one of type, id, industry_id
can be used slug
在你的数组中没有被定义,只能使用type, id, industry_id
中的一个
Ad 1. 广告1。
Correct way is: 正确的方法是:
foreach ($newsLists['News'] as $newsList) {
echo '<li>' . $newsList['type'] . '</li>'; // you can switch type to id or industry_id
}
The resolution involves creating another loop since there is a has many relationship between industry and news. 该决议涉及创建另一个循环,因为行业和新闻之间存在许多关系。 This extra loop allows the news stories to be looped through. 这个额外的循环允许循环播放新闻报道。
<?php foreach ($newsLists as $newsList): ?>
<ul>
<?php foreach ($newsList ['News'] as $list): ?>
<li><?php echo $list['slug']; ?></li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.