php array undefined index

时间:2015-09-18 17:33:39

标签: php arrays multidimensional-array indexing

我搜索了google和堆栈溢出论坛,他们反复说使用isset()来确保定义索引,但是如果没有设置索引,很少有人知道该怎么做。

这是我的简单代码:

<?php
    $allStaff = $this->registry->getData('staff');
    $departments = array();
    foreach($allStaff as $staff){
        if(isset($departments[$staff['department']])){
            $departments[$staff['department']][count($departments[$staff['department']])] = $staff;
        }
        else {
            $departments[$staff['department']][count($departments[$staff['department']])] = $staff;
        }

idexing系统的一个例子是:$ departments [&#39; Management&#39;] [0] [&#39; name / staff position / etc&#39;]

在我查看其他用户的一些答案时,我尝试过设置$ department [$ staff [&#39; department&#39;]] = 0,但它不起作用并且给我带来更多错误。请帮助,谢谢

2 个答案:

答案 0 :(得分:1)

它会给你带来问题的地方在这里:

count($departments[$staff['department']])

因此,您要确保为其分配了兼容性,然后您可以使用它:

if (!isset($departments[$staff['department']]))
    $departments[$staff['department']] = array();

$departments[$staff['department']][count($departments[$staff['department']])] = $staff;

PHP将默认为您处理顺序数字索引,因此您可以将上述内容简化为(感谢BNC的灵感):

if (!isset($departments[$staff['department']]))
    $departments[$staff['department']] = array();

$departments[$staff['department']][] = $staff;

请注意,您的代码有P[Q[i]][j] = Q这样的模式,可以正常工作,只是不经常看到。

答案 1 :(得分:0)

目前还不清楚你在这里要做什么。我猜你想要计算每个部门有多少工作人员。如果我猜错了,请用英文(不是代码)说出你的目标。如果我的猜测是正确的,......

$allStaff = $this->registry->getData('staff');
$departments = array();
foreach($allStaff as $staff){
    if( !isset($departments[$staff['department']]) ) {
        $departments[$staff['department']] = 0;
    }
    $departments[$staff['department']] += 1;
}

更新:等等,我想我只是想通了(当count()足以附加到数组时,我被[]误导了。我现在猜你想要按部门分组的工作人员......

$allStaff = $this->registry->getData('staff');
$departments = array();
foreach($allStaff as $staff){
    if( !isset($departments[$staff['department']]) ) {
        $departments[$staff['department']] = array();
    }
    $departments[$staff['department']][] = $staff;
}