开发者

merging arrays to each other

I have these two arrays. I want array b to be merged into array 1 and apples show under 开发者_运维技巧product[0], oranges in product[1] and lemon in product[2]:

$a = Array
(
    [0] => Array
    (
        [Customer] => Array
        (
            [id] => 46714
        )
        [Product] => Array
        (
            [id] => 148  
        )
    )       
    [1] => Array
    (
        [Customer] => Array
        (
            [id] => 46714              
        )
        [Product] => Array
        (
            [id] => 148
        )   
    )
    [2] => Array
    (
        [Customer] => Array
        (
            [id] => 46714                           
        )
        [Product] => Array
        (
            [id] => 148  
        )
    )
)

$b = array(     
    [0] => apples
    [1] => Orange
    [2] => Lemon
)


foreach($b as $key => $value) {
  $a[$key]['fruit'] = $value;
}

That would add them based on the current order. Giving you $a[0]['fruit'] = Apples, $a[1]['fruit'] = Orange and $a[2]['fruit'] = "Lemon". I'm not sure if that's what you need, can't completely understand your question.


Something like?

foreach ($b as $key => $value)
{
  $a[$key]['product'][] = $value;  
}

You need to specify your desired result for a more accurate guess.


You could follow the other examples, but you could spare yourself an unneeded iteration by modifying your $b array and merging the two:

// Modify your $b array to mimic the structure of your $a array
$b = array(     
    [0] => array('Product' => 'apples'),
    [1] => array('Product' => 'Orange'),
    [2] => array('Product' => 'Lemon')
);

// Merge the two arrays into $a
$a = array_merge($a, $b);

Generally it's best to use PHP's compiled code as it will out perform any code you can write yourself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜