Search code examples
phparraysmultidimensional-arraycomparison

compare two multidimensional arrays of object and set new property true/false pending match on larger set


I Have an array of objects example:

Larger Set:

Array(
    [0] stdClass Object(
                        [ID] => 1,
                        [name] => monkey,
                        [sub] => help
                       ),
    [1] stdClass Object(
                        [ID] => 1,
                        [name] => tooth,
                        [sub] => tip
                       ),
    [2] stdClass Object(
                        [ID] => 1,
                        [name] => who,
                        [sub] => knows
                       ),
    )

Smaller Set

Array(
    [0] stdClass Object(
                        [ID] => 1,
                        [name] => monkey,
                        [sub] => help
    )

Desired out come:

Array(
    [0] stdClass Object(
                        [ID] => 1,
                        [name] => monkey,
                        [sub] => help,
                        [selected] => yes
                       ),
    [1] stdClass Object(
                        [ID] => 1,
                        [name] => tooth,
                        [sub] => tip,
                        [selected] => no
                       ),
    [2] stdClass Object(
                        [ID] => 1,
                        [name] => who,
                        [sub] => knows,
                        [selected] => no
                       ),
    )

What I am trying to play with which doesn't seem to be working is

    foreach($result_static as $stock)
    {
        foreach($result_memb as $memb_choice)
        {
            $stock->selected = "false";
            //echo $stock->name .' == '. $memb_choice->name.'<br>';
            if($stock->name == $memb_choice->name)
            {
                $stock->selected = "yes";
            }
        }
        $output[] = $stock;
    }

This doesn't appear to be matching any of the actual results, and from what I gather my foreach logic is off cause either due to it relooping the second loop so many times or the first one withing the other this way, the names from each never match respectively the way I would hope. So I am trying to look for ideas on how to better tackle this, and hopefully something a bit more optimized would be nice, but Ill take what I can get currently.


Solution

  • Try This

    foreach($result_static as $stock)
        {
            $stock->selected = "false";
            foreach($result_memb as $memb_choice)
            {
                if($stock->name == $memb_choice->name)
                {
                    $stock->selected = "yes";
                }
            }
            $output[] = $stock;
        }