2011-05-06 122 views
1

我有这两个数组。我想阵列b合并到阵列1 product[0]下​​显示,orangesproduct[1]lemonproduct[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 
) 
+0

或者你刚刚忘记显示'$ b'数组,因此无法回答问题吗? – Orbling 2011-05-06 22:59:37

+0

替换它,ID旁边的另一个字段(如果是,称为)? – Autolycus 2011-05-06 23:00:50

回答

2

喜欢的东西?

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

您需要指定您想要的结果以获得更准确的猜测。

+2

嗯,在我的例子中使用$ k会更容易是的,哈哈:-) – 2011-05-06 23:05:02

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

这会根据当前订单添加它们。给你$ a [0] ['fruit'] =苹果,$ a [1] ['fruit'] =橙和$ a [2] ['fruit'] =“柠檬”。我不确定这是否是你需要的,不能完全理解你的问题。

+0

在这种情况下'$ k'将等于'$ i',并且必须潜在地跳过值,所以我将免去'$ i'完全。我会对此表示赞赏,但不会使用单字母变量,但使用'['fruit']'键实际上比其他答案更好。 – Orbling 2011-05-06 23:06:42

+0

是的,我注意到jeroen的$ k部分。我已经用笔记更改了代码。 – 2011-05-06 23:09:31

+0

这样比较好。 :-) – Orbling 2011-05-06 23:09:44

0

你可以按照其他的例子,但是你可以通过修改$ B阵列和合并两个饶了自己不需要的迭代:

// 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); 

一般来说,最好使用PHP的编译后的代码,因为它会出来执行你可以编写自己的任何代码。