Need Help merging 2 arrays

Discussion in 'PHP' started by yelbom, Dec 18, 2010.

  1. #1
    I have 2 arrays that are not equal but need to merge them into 1 array

    $a = array('books',
    'clothes',
    'dvds',
    'jewelry',
    'toys');

    $b = array('0001',
    '0001',
    '0001',
    '0001',
    '0001',
    '0002',
    '0002',
    '0002',
    '0002',
    '0002');

    Final need merge the arrays like this:

    $merge = array('0001,books',
    '0001,clothes',
    '0001,dvds',
    '0001,jewelry',
    '0001,toys',
    '0002,books',
    '0002,clothes',
    '0002,dvds',
    '0002,jewelry',
    '0002,toys');

    Thanks
     
    yelbom, Dec 18, 2010 IP
  2. tvoodoo

    tvoodoo Active Member

    Messages:
    239
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    53
    #2
    
    <?php
        //the function that makes the merge as you want it to be :
        function customMerge($a,$b)
        {
            $ret = array();
            
            if(is_array($a) && count($a) > 0 && is_array($b) && count($b) > 0)
            {
                $rounds = count($b) / count($a);
                for($i = 0 ; $i < $rounds ; $i++)
                {
                    foreach($a as $key=>$value)
                    {
                        $b_val = $b[$i+(count($a)*$i)];
                        array_push($ret,$b_val.','.$value);        
                    }
                }
            }
            return $ret;
        }
        
        //define your array's
        $a = array('books','clothes','dvds','jewelry','toys');  
        $b = array('0001','0001','0001','0001','0001','0002','0002','0002','0002','0002');
        
        //run and print the resulting array
        echo '<pre>';
        print_r(customMerge($a,$b));
        echo '</pre>';
    ?>
    
    PHP:
     
    tvoodoo, Dec 18, 2010 IP
  3. yelbom

    yelbom Greenhorn

    Messages:
    36
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    16
    #3
    tvoodoo, Thanks for your help!
     
    yelbom, Dec 18, 2010 IP
  4. tvoodoo

    tvoodoo Active Member

    Messages:
    239
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    53
    #4
    You're welcome.
     
    tvoodoo, Dec 18, 2010 IP