我搜索了谷歌和堆栈溢出论坛,他们反复说使用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;
}
标识系统的一个例子是:$departments['Management'][0]['name/staff position/etc']
我试过把$departments[$staff['department']] = 0,因为我看了其他用户的一些答案,但它不起作用,给了我更多的错误。请帮忙,谢谢
这会给你带来问题:
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
,将工作正常,只是不经常看到。
不清楚您在这里要做什么。我猜你是想数一下每个部门有多少员工。如果我猜错了,请用英语陈述你的目标(不是代码)。如果我猜对了,…
$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;
}