多维数组 - PHP - CodeIgniter

时间:2014-03-27 13:38:09

标签: php arrays codeigniter

我正在使用CodeIgniter和Jamie Rumbelow的My_Model加入3个表以获取数据库中的以下结果:

Career_Option            Course               Specialization
-------------            -------              --------------
Management               MBA                  Finance
Management               BBA                  Marketing
Engineering              BSc                  Computer Science
Engineering              MSc                  Bio-Technology 

这是我的结果集从我的模型类传递给控制器​​时的外观:

Array
(
    [0] => stdClass Object
        (
            [career_option] => Management
            [course] => MBA
            [specialization] => Finance
        )

    [1] => stdClass Object
        (
            [career_option] => Management
            [course] => BBA
            [specialization] => Marketing
        )

    [2] => stdClass Object
        (
            [career_option] => Engineering
            [course] => Bsc
            [specialization] => Computer Science
        )

    [3] => stdClass Object
        (
            [career_option] => Engineering
            [course] => MSc
            [specialization] => Bio-Technology
        )
)

现在,在我的网页上,我想以下列方式显示此结果集:

Management
|
|_ MBA
|   |
|   |_ Finance
|
|_ BBA
    |
    |_ Marketing

Engineering
|
|_ BSc
|   |
|   |_ Computer Science
|
|_ MSc
    | 
    |_ Bio-Technology

你能否建议我在控制器中创建一个数组(多维?)来保存这些记录,我最终会传递给我的视图?

谢谢!

2 个答案:

答案 0 :(得分:0)

这对你有用吗?


function tree_from_rows($rows)
{
    $tree = array();
    foreach($rows as $row) {
        $ref =& $tree;
        foreach($row as $value) {
            if (!array_key_exists($value, $ref)) {
                $ref[$value] = array();
            }
            $ref =& $ref[$value];
        }
    }
    return $tree;
}

请注意,大多数内部分支也是数组,因此在迭代数组时,您只需要使用索引。

答案 1 :(得分:0)

例如,假设您的数组位于名为$results的变量中,您可以执行以下操作

$aData['careerOptions'] = array();
foreach($results as $result) {
    if(!in_array($result->career_option, $aData['careerOptions'])) {
        $aData['careerOptions'][] = $result->career_option;
    }
    if(!in_array($result->course, $aData['careerOptions'][$result->career_option])) {
        $aData['careerOptions'][$result->career_option][] = $result->course;
    }
    if(!in_array($result->specialization, $aData['careerOptions'][$result->career_option][$result->course])) {
        $aData['careerOptions'][$result->career_option][$result->course][] = $result->specialization;
    }
}

然后,您可以通过

$aData传递给您的视图
$this->load->view('path/to/view', $aData);

一旦进入您的视野,您就可以访问包含您的数组的$careerOptions