3

I have two objects arrays.

First array $x:

[0] => stdClass Object
    (
        [id] => 54
        [value] => test54
        [something] => testtest54
    )

[1] => stdClass Object
    (
        [id] => 21
        [value] => test21
        [something] => testtest21
    )
...

Second array $y:

[0] => stdClass Object
    (
        [id] => 21
        [value] => test21_new_value
    )

[1] => stdClass Object
    (
        [id] => 54
        [value] => test54_new_value
    )
...

I want to update my first array $x importing value of the second array's ($y) field which has the same id, I want to have :

[0] => stdClass Object
    (
        [id] => 54
        [value] => test54_new_value
        [something] => testtest54
    )

[1] => stdClass Object
    (
        [id] => 21
        [value] => test21_new_value
        [something] => testtest21
    )
...

I can do something like this :

foreach($x as $k => $v) {
    foreach($y as $k2 => $v2) {
        if ($v->id === $v2->id) $x[$k]->value = $v2->value;
    }
}

But I don't like this, because I have to walk on array $y for each $x (if I have 100 items in $x and 100 items in $y, it loops 100*100 times). I think there is a more efficient, elegant or optimized way to do this, but I don't know how to do that (I did not found a precise response to this specific problem, so I ask here).

0

1 Answer 1

2

Sure. Usually you'd use an associative array for this (with the key being the unique ID), as this would mean (100 + 100) iterations instead of (100 * 100):

<?php
    $assocX = array();
    foreach ($x as $v) {
        $assocX[$v->id] = $v;
    }

    foreach ($y as $v) {
        $v->something = $assocX[$v->id]->something;
    }
?>

If you can't be sure that the value exists in $x you can also check for this ("no value" would be translated to NULL):

<?php
    $assocX = array();
    foreach ($x as $v) {
        $assocX[$v->id] = $v;
    }

    foreach ($y as $v) {
        $v->something = (isset($assocX[$v->id]) ? $assocX[$v->id]->something : null);
    }
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Ok thanks a lot ! Actually, the & isn't necessary with objects arrays, I think. $v already is a reference to an object (I've just tried with one loop, but maybe I'm wrong or I don't understood)
@rap-2-h You're right. Objects are always passed by reference (forgot that - it's late-ish!) :)

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.