PHP 5.4 code update - creating a default object from empty values ​​in the foreach and objects array

I have the following code:

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

If I add:

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

to fix it. Then the values ​​in the objects in the array "bar" are not specified. For example, I have an array:

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

At the output, I should get:

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

But in practice, I get:

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

How do I update the code to make it work?

+5
source share
2 answers

Problem:

The problem with your code is that if you use the first try,

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

an empty default object will be created if you use the operator ->for the index of a nonexistent array. (ZERO). You will receive a warning as this is a bad coding practice.

Second attempt

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

$bar[$i] .

Btw 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);
+6

$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
+1

All Articles