2013-02-27 215 views
0

我有2 x二维数组与数据库返回值。php合并2个阵列

目前我在做一个foreach循环,并把返回的值到一个单独的表,每个阵列:

如:

<table> 
    <tr> 
     <td>Auto Bavaria Midrand BMW</td> 
     <td>63</td> 
     <td>39</td> 
    </tr> 
    ... 
</table> 
<table> 
<tr> 
    <td>Auto Bavaria Midrand BMW</td> 
    <td>40</td> 
    <td>15</td> 
    ... 
</tr> 
</table> 

但我需要在此格式返回值,只有1表:

<table> 
    <tr> 
    <td>Auto Bavaria Midrand BMW</td> 
    //the name of the record does not need to be repeated, only the values 
    <td>63</td> 
    <td>39</td> 
    <td>40</td> //values from 2nd array 
    <td>15</td> // values from 2nd array 
    </tr> 
     ...//next record set 
</table> 

Array 
(
    [0] => Array 
     (
      [DealerName] => Auto Bavaria Midrand BMW 
      [dealersContacted] => 63 
      [DealerContact_Y] => 39 
      [DealerContact_N] => 15 
      [DealerShipId] => 21730 
      [DataId] => 23527 
     ) 
    //extra returned records 
) 

Array 
(
    [0] => Array 
     (
      [DealerName] => Auto Bavaria Midrand BMW 
      [dealersContacted] => 65 
      [DealerContact_Y] => 40 
      [DealerContact_N] => 15 
      [DealerShipId] => 21730 
      [DataId] => 23527 
     ) 

    //extra returned records 
) 

我可以做PHP的一面,我的问题是如果有一个数组函数,可以只合并数组的所需位?我已经搜索,越来越困惑。

+0

我认为他给出的两个例子应该是不同的。是的,你需要自己循环通过阵列 - 没有神奇的内置功能。 – zaf 2013-02-27 09:21:37

回答

0

从数据库中获取数据时,您应该更改构建数组的方式,以便代替无意义的数字索引,获得有意义的键。在你上面的例子中,你可能想用DealerName作为关键。这样,当您检索物品时,只需将它们添加到适当的位置即可。例如:

while($rows = fetch_from_db($res)) { 
    $output[$rows['DealerName']]['dealersContacted'] = $rows['dealersContacted']; 
    $output[$rows['DealerName']]['DealerContact_Y'] = $rows['DealerContact_Y']; 
    // Add more keys here 
} 

这样,当您完成检索两个结果集时,只剩下一个数组。您还应该计划如何处理双重索引,例如您的示例中提及的经销商。

+0

谢谢,这很有意义。 – user1882752 2013-02-27 09:24:55