6

我有以下代码:

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

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

4

2 回答 2

7

问题:

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

$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);
于 2013-02-05T14:35:53.800 回答
1

尝试

$bar = array();
foreach($foo as $n=>$ia)
   foreach($ia as $i=>$v)
      $bar[] = (object) array($n => $v);

这应该给你:

$bar[0]->somefield = value1
$bar[1]->somefield = value2
$bar[2]->somefield = value3
$bar[3]->anotherfield = value1
$bar[4]->anotherfield = value2
$bar[5]->anotherfield = value3
于 2013-02-05T14:32:34.383 回答