PHP 5.4代码更新 – 从foreach和objects数组中的空值警告创建默认对象
发布时间:2020-09-01 05:25:07 所属栏目:PHP 来源:互联网
导读:我有以下代码: 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; 要解决
我有以下代码: 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,上面的代码也无法正常工作 解: 我更喜欢以下代码示例,因为: >它没有警告:) 码: <?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); (编辑:甘南站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |