CodeIgniter - 嵌套的foreach - 按年显示数据

时间:2012-11-10 17:32:59

标签: php codeigniter loops foreach nested-loops

我正在制作一些必须使用年份作为暴露值的脚本。这些信息保存在数据库中,我必须把它拉出来,但这不是问题。我必须创建列表,其中多年暴露为主要值。我正在处理代码,但我总是遇到错误。

控制器:

$data['dbdata'] = $this->DBdata->serve_val('pc_year');
foreach ($data['dbdata']->result() as $data)
{
    $data['sheet'] = $this->DBdata->serve_val('pc');
    foreach ($data['sheet']->result() as $sht)
    {
        $data['vdata'][$data->idyr][$sht->idpc]['name'] = $sht->name;
        $data['vdata'][$data->idyr][$sht->idpc]['properties'] = $sht->properties;
    }
}

查看:

foreach ($dbdata->result() as $data)
{
    echo $data->year."<br>";
    foreach ($sheet->result() as $sht)
    {
        echo $vdata[$data->idyr][$sht->idpc]['name']."<br>";
        echo $vdata[$data->idyr][$sht->idpc]['properties']."<br>";
        echo "<br>";
    }
}

错误:

A PHP Error was encountered

Severity: Notice

Message: Undefined offset: 1

如何正确地做到这一点?

1 个答案:

答案 0 :(得分:1)

您需要更改控制器,因为您无法重新指定变量名称

控制器:

$data['dbdata'] = $this->DBdata->serve_val('pc_year');
foreach ($data['dbdata']->result() as $result)
{
    $result['sheet'] = $this->DBdata->serve_val('pc');
    foreach ($result['sheet']->result() as $sht)
    {
        $data['vdata'][$result->idyr][$sht->idpc]['name'] = $sht->name;
        $data['vdata'][$result->idyr][$sht->idpc]['properties'] = $sht->properties;
    }
}

查看:

foreach ($dbdata->result() as $data)
{
    echo $data->year."<br>";
    foreach ($sheet->result() as $sht)
    {
        echo $vdata[$data->idyr][$sht->idpc]['name']."<br>";
        echo $vdata[$data->idyr][$sht->idpc]['properties']."<br>";
        echo "<br>";
    }
}