Sebastian Rush
Sebastian Rush

Reputation: 538

PHP stdClass issue

I try to create an generic object which needs to be structuered like this:

[Content] => stdClass Object
    (
        [item] => Array
            (
                [0] => stdClass Object
                    (
                        [Value] => STRING
                    )

            )
        [item] => Array
            (
                [0] => stdClass Object
                    (
                        [Value] => ANOTHER STRING
                    )
            )
    )

This is my code:

$content = new stdClass();
$data = file('filname.csv');

foreach($data as $key => $val) {
    $content->item->Value = $val;
}

This overwrites itself each time the loop iterates. By defining item as an array like this:

$content->item = array();
...
$content->item[]->Value = $val;

...the result is also not the estimated.

Upvotes: 0

Views: 62

Answers (1)

marian0
marian0

Reputation: 3337

You are overwritting data each time even using array. You should create temporary object for storing value and then put them to item array.

$content = new \stdClass();
$content->item = array();

foreach($data as $key => $val) {
    $itemVal = new \stdClass();
    $itemVal->Value = $val;
    $content->item[] = $itemVal;
}

Upvotes: 3

Related Questions