gpt4 book ai didi

PHP 5.4 代码更新 - 从 foreach 和对象数组中的空值警告创建默认对象

转载 作者:可可西里 更新时间:2023-11-01 13:18:00 25 4
gpt4 key购买 nike

我有以下代码:

foreach($foo as $n=>$ia) {
foreach($ia as $i=>$v) {
$bar[$i]->$n = $v; //here I have 'Creating default object...' warning
}
}

如果我添加:

$bar[$i] = new stdClass;
$bar[$i]->$n = $v;

修复它。然后数组“bar”中的对象中的值未设置。例如,我有数组:

 $foo = array(
"somefield" => array("value1", "value2", "value3"),
"anotherfield" => array("value1", "value2", "value3")
);

关于输出我应该得到:

$bar[0]->somefield = value1
$bar[1]->anotherfield = value2

但实际上我得到:

$bar[0]->somefield = null //(not set)
$bar[1]->anotherfield = null //too

我应该如何更新代码以使其正常工作?

最佳答案

问题:

你的代码的问题是,如果你使用第一次尝试,

$bar[$i]->$n = $v;

如果您在不存在的数组索引上使用 -> 运算符,将创建一个默认的空对象。 (无效的)。您会收到警告,因为这是一种糟糕的编码习惯。

第二次尝试

$bar[$i] = new stdClass;
$bar[$i]->$n = $v;

将在每次循环覆盖 $bar[$i] 时简单地失败。

顺便说一下,上面的代码即使在 PHP5.3 下也无法工作


解决方案:

我更喜欢下面的代码示例,因为:

  • 它在没有警告的情况下工作:)
  • 它不像您的问题那样使用内联初始化功能。我认为将 $bar 显式声明为空 array() 并使用 new StdClass() 创建对象是一种很好的编码习惯。
  • 它使用描述性变量名称帮助理解代码的作用。

代码:

<?php

$foo = array(
"somefield" => array("value1", "value2", "value3"),
"anotherfield" => array("value1", "value2", "value3")
);

// create the $bar explicitely
$bar = array();

// use '{ }' to enclose foreach loops. Use descriptive var names
foreach($foo as $key => $values) {
foreach($values as $index => $value) {
// if the object has not already created in previous loop
// then create it. Note, that you overwrote the object with a
// new one each loop. Therefore it only contained 'anotherfield'
if(!isset($bar[$index])) {
$bar[$index] = new StdClass();
}
$bar[$index]->$key = $value;
}
}

var_dump($bar);

关于PHP 5.4 代码更新 - 从 foreach 和对象数组中的空值警告创建默认对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14709826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com