Array merge based on key

Discussion in 'PHP' started by vale73, Dec 1, 2010.

  1. #1
    hi,
    I've got two php arrays

    The first array represents the total distance covered by a car, and I call it

    $a

    Array ( [0] => stdClass Object ( [total_distance] => 1000 [car_id] => 1 ) [1] => stdClass Object ( [total_distance] => 500 [car_id] => 2 ) )

    The second array, is the array of cars, and I call it

    $b

    Array ( [0] => stdClass Object ([car_id] => 1 [year] => 2008 ) [1] => stdClass Object ( [car_id] => 2 [year] => 2010 ) )

    Is it possible to merge these arrays, provided they have the car_id key in common?
    The resulting array should be:

    $c

    Array ( [0] => stdClass Object ([car_id] => 1 [year] => 2008 [total_distance] => 1000 ) [1] => stdClass Object ( [car_id] => 2 [year] => 2010 [total_distance] => 500 ) )
     
    vale73, Dec 1, 2010 IP
  2. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #2
    
    <?php
    
    /*
    Object merge and in Object functions
    */
    
    function object_merge($objectFrom,$objectTo,$indexUse)
    {
        $objectReturn = array();
        foreach($objectFrom as $curObject)
        {        
            $index = in_object($indexUse,$curObject->$indexUse,$objectTo,true);
            if(is_int($index))
            {
                foreach($objectTo[$index] as $indexName => $indexValue)
                {
                    $curObject->$indexName = $indexValue;
                }
            }
            $objectReturn[] = (object) $curObject;        
        }
        return $objectReturn;
    }
    
    function in_object($searchFor,$searchValue,$objectSearch,$returnResult)
    {
        foreach($objectSearch as $index => $thisObject)
        {
            if($thisObject->$searchFor == $searchValue)
            {
                if($returnResult)
                {
                    return $index;
                } else {
                    return true;
                }
            }
        }
        return false;
    }
    
    // Usage
    $obj1[0] = (object) array('catId' => 1, 'catName' => 'Name');
    $obj1[1] = (object) array('catId' => 2, 'catName' => 'Name2');
    
    $obj2[0] = (object) array('catId' => 1, 'catDesc' => 'Desc');
    $obj2[1] = (object) array('catId' => 2, 'catDesc' => 'Desc2');
    
    $obj_merged = object_merge($obj1,$obj2,'catId');
    print_r($obj_merged);
    
    ?>
    
    PHP:
    This should work for you.
     
    ThePHPMaster, Dec 1, 2010 IP