我是CI的新手。使用codeigniter,我正在尝试打印类别及其项目如下:
第1类名称
第2类名称
第3项
第4项
第5项
等等。 我在控制器中构建了一个数组和子数组,如下所示:
$data['categories'] = $this->publicpages_model->getcategories();
foreach($data['categories'] as $category)
{
$data['categories'][$category->cID]= $this->publicpages_model->getitems($category->cID);
}
在视图中,我尝试使用以下代码,但我无法完成它以获得所需的输出,如上所述。
foreach($categories AS $category)
{
echo '<h1>' . $category->name . '</h1>';
//Missing code to print the items
echo "<br>";
}
虽然打印了类别名称,但我也收到以下错误:
Severity: Notice
Message: Trying to get property of non-object
print_r($ categories)给出以下结果:
Array ( [0] => stdClass Object ( [cID] => 1 [name] => Breakfast ) [1] => Array ( [0] => stdClass Object ( [itemID] => 1 [name] => Aaloo Paratha [description] => descriptio 1 [menu] => 1 [price] => 22 [tax] => 20 [sStatus] => ) ) [2] => stdClass Object ( [cID] => 7 [name] => Fast Food ) [5] => Array ( [0] => stdClass Object ( [itemID] => 5 [name] => Missi Roti [description] => Hot and Crunchy [menu] => 5 [price] => 5 [tax] => 1 [sStatus] => 1 ) ) [7] => )
vardump给出以下输出:
array(5) { [0]=> object(stdClass)#22 (2) { ["cID"]=> string(1) "1" ["name"]=> string(9) "Breakfast" } [1]=> array(1) { [0]=> object(stdClass)#25 (7) { ["itemID"]=> string(1) "1" ["name"]=> string(13) "Aaloo Paratha" ["description"]=> string(12) "descriptio 1" ["menu"]=> string(1) "1" ["price"]=> string(2) "22" ["tax"]=> string(2) "20" ["sStatus"]=> string(0) "" } } [2]=> object(stdClass)#24 (2) { ["cID"]=> string(1) "7" ["name"]=> string(9) "Fast Food" } [5]=> array(1) { [0]=> object(stdClass)#26 (7) { ["itemID"]=> string(1) "5" ["name"]=> string(10) "Missi Roti" ["description"]=> string(15) "Hot and Crunchy" ["menu"]=> string(1) "5" ["price"]=> string(1) "5" ["tax"]=> string(1) "1" ["sStatus"]=> string(1) "1" } } [7]=> bool(false) }
请帮助解决方案。
答案 0 :(得分:1)
您的代码中存在一些问题。你想做的事情很好,但你怎么做就是问题。
在这个foreach循环中,您正在修改循环的相同数组;因此它完全打破了$data['categories']
数组的结构。因此,数组的第二个元素没有name
键,因此会抛出该警告。
foreach($data['categories'] as $category)
{
$data['categories'][$category->cID] = ...;
}
如果您尝试获取每个类别的子项,并将它们添加为新键,则需要修改$category
数组。不是外部数组:)所以改变它就像这样。
foreach($data['categories'] as $category)
{
$category->subItems = $this->publicpages_model->getitems($category->cID);
}
或者,如果您想要$category->cID
而不是密钥subItems
,则可以将上述内容更改为:
foreach($data['categories'] as $category)
{
$category->{$category->cID} = $this->publicpages_model->getitems($category->cID);
}
我希望它有所帮助:)如果不清楚,请随时提出任何问题。
答案 1 :(得分:0)
尝试以下代替
您的控制器
$data['categories'] = $this->publicpages_model->getcategories();
foreach($data['categories'] as $category)
{
$category->arrItems = $this->publicpages_model->getitems($category->cID);
}
您的观点
foreach($categories AS $category)
{
echo '<h1>' . $category->name . '</h1>';
if (isset($category->arrItems) && is_array($category->arrItems))
{
foreach($category->arrItems AS $objItem)
{
print_r($objItem);
}
}
echo "<br>";
}