Php如何循环遍历多维数组

时间:2015-09-13 09:35:06

标签: php arrays multidimensional-array

如何按如下方式循环遍历多维数组,并通过键名获取键及其值?

 $leaveTypes = (object) [
                 [
                   "name" => "Holiday",
                   "colour" => "#cc6699",
                   "deducted" => true,
                 ],
                 [
                   "name" => "Sick Leave",
                   "colour" => "#996666",
                   "deducted" => false,
                ]
             ];

     foreach($leaveTypes as $leaveType)
     {
           $someVariable = $leaveType->name;

     }

上面给出了一个错误:尝试获取非对象的属性。

1 个答案:

答案 0 :(得分:2)

您正在访问数组而不是对象,因此您应该使用数组语法:

foreach($leaveTypes as $leaveType)
{
    $someVariable = $leaveType['name'];
}

编辑:您使用(object)演员更改了很多问题,在这种情况下,您需要一个对象数组,以便您可以循环播放它们:

$leaveTypes = [
    (object) [
        "name" => "Holiday",
        "colour" => "#cc6699",
        "deducted" => true,
    ],
    (object) [
        "name" => "Sick Leave",
        "colour" => "#996666",
        "deducted" => false,
    ]
];
foreach($leaveTypes as $leaveType)
{
    $someVariable = $leaveType->name;
}

这两个解决方案实际上是相同的,关联数组很好。