Foreach循环以一种方式工作,而不是另一种方式

时间:2014-06-01 22:17:42

标签: php arrays multidimensional-array foreach

我似乎遇到了一些循环遍历数据数据的问题,它以一种方式工作,但不是我想要的方式。

我应该预先假定数组由两个变量$departments$_UNIQUECONSTANT['departments']表征。任何有助于持续工作的帮助都会很棒。

数组

Array (
    [departments] => Array (
        [0] => Array (
            [id] => 2
            [name] => Support
            [description] => Support Department
        )
        [1] => Array (
            [id] => 3
            [name] => Accounting
            [description] => Accounting Department
        )
    )
)

工作职能。

foreach($departments as $department){
    $department['id'];
}

我需要工作的功能。

foreach($_UNIQUECONSTANT['departments'] as $department){
    $department['id'];
}

1 个答案:

答案 0 :(得分:1)

以下是两种应该有效的方法:

注意:我没有测试它们

define('_UNIQUECONSTANT', serialize(array()));

$d = unserialize(_UNIQUECONSTANT);

foreach($d["departments"] as $department){
    $department['id'];
}

// Newer PHP versions
foreach(unserialize(_UNIQUECONSTANT)["departments"] as $department){
    $department['id'];
}