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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了PHP 5.4代码更新 – 从foreach和objects数组中的空值警告创建默认对象脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码
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","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明确地声明为空数组()并使用:new StdClass()创建对象是一种很好的编码实践.
>它使用描述性变量名称有助于理解代码正在做什么.

码:

<?PHP

$foo = array(
  "somefield" => array("value1","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和objects数组中的空值警告创建默认对象全部内容,希望文章能够帮你解决PHP 5.4代码更新 – 从foreach和objects数组中的空值警告创建默认对象所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。