php - PHP 7 Multidimensional Array Initialization
问题描述
I wrote these PHP scripts maybe 10 years ago, most likely on PHP 4, but maybe on 3. I worked on them a couple years ago and got them to work on PHP 5, but now my host has upgraded to PHP 7, and I am throwing undefined offset errors by the hundreds if not thousands. I was under the impression that if I try to load a value into an undefined array, that it would create the index, but apparently not. So my solution is to simply create the empty array to avoid this. I am just trying to determine if nested loops are the only solution. We are a preschool, and for my first script, my arrays are things like:
$childs_classroom[classroom][week][day_of_week]
classroom is 0-4, weeks 0-260, and dow 0-4
When I try to increment an array like this, it creates an undefined offset error every time (I believe). Is there a simpler way other than nested loops to create this array and fill it with nulls/zeroes so I don't get errors? I apologize if this is basic stuff, I've forgotten more about PHP than I remember atm.
解决方案
如果您分配嵌套数组,它们确实会自动创建(没有通知错误),但是由于您说incrementing,听起来好像您在初始化之前访问该值。增加不存在的变量或键$var++
会导致警告,因为它等于$var = $var + 1
,并且在变量存在之前评估右侧。
这可以通过首先将密钥设置为零来避免。
在 PHP7 中,一个简单的方法是使用$var ??= 0
. 如果它不包含非零值,它将初始化$var
为0
,但不会覆盖现有的非零值。
例如,以下代码将初始化一个数组键,然后将其递增两次,而不会发出 e_notice 警告。
$non_existent_array['non_existent']['key'] ??= 0;
$non_existent_array['non_existent']['key']++;
var_dump($non_existent_array);
$non_existent_array['non_existent']['key'] ??= 0;
$non_existent_array['non_existent']['key']++;
var_dump($non_existent_array);
array(1) {
["non_existent"]=>
array(1) {
["key"]=>
int(1)
}
}
array(1) {
["non_existent"]=>
array(1) {
["key"]=>
int(2)
}
}
推荐阅读
- javascript - 尝试通过 paypal api 创建付款时如何解决响应:{type: "cors"}
- java - 按对象属性分组
- reactjs - 反向代理到静态网站不起作用
- python - 围绕 Flask SqlAlchemy 查询简化一对 if-else 语句
- c# - 在 Visual Studio 2019 中的 Xamarin 中捕获 Xaml 错误的最佳方法是什么?
- jsf - 如何在 p:calendar 中将滑块/选择器初始值设置为“值”?
- c# - SqlDataReader - 使用所有匹配项填充子列表
- javascript - 使用ajax发送ip和接收位置
- javascript - 承诺没有按顺序解决
- rest - 多个客户端调用的 RESTApi 问题