0

I have an object with some variables for events (id, date, time, etc) gathered from a database. Some events have multiple days per week, so I want to duplicate the event object for each day listed and mark which day it's being duplicated for.

For example, I have this object inside an array:

Array
(
[0] => stdClass Object
    (
        [id] => 1
        [days] => Array
            (
                [0] => Mon
                [1] => Tues
            )
    )
)

and I'd like it to look like this:

Array
(
[0] => stdClass Object
    (
        [id] => 1
        [day] => Mon
        [days] => Array
            (
                [0] => Mon
                [1] => Tues
            )
    )

[1] => stdClass Object
    (
        [id] => 1
        [day] => Tues
        [days] => Array
            (
                [0] => Mon
                [1] => Tues
            )
    )
)

For some reason, when it loops through the second time the object is getting updated in the 0 position of the main array and the 1 position like so:

Array
(
[0] => stdClass Object
    (
        [id] => 1
        [day] => Tues
        [days] => Array
            (
                [0] => Mon
                [1] => Tues
            )
    )

[1] => stdClass Object
    (
        [id] => 1
        [day] => Tues
        [days] => Array
            (
                [0] => Mon
                [1] => Tues
            )
    )
)

This is a replication of the array declaration and loop I'm using:

$out = array();
$arr = array();
$arr[0] = new stdClass();
$arr[0]->id = 1;
$arr[0]->days = array("Mon","Tues");

foreach($arr as $a){
    foreach($a->days as $day){
        $a->day = $day;
        $out[] = $a;
    }
}

I did the same thing with straight arrays (cast the object as an array) and there it worked as I hoped, but it'd be nice to know how to do it with objects as well.

Any ideas?

0

1 Answer 1

4

You've got a single object, $a, referenced from both spots in the array. To duplicate the object instead use $out[] = clone $a; in place of $out[] = $a;.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.