2017-09-13 181 views
0

我使用不同的键从MySQL卸载4个不同的表。我需要将它们组合成一个数组。我会按日期排序(但它不重要,我知道如何去做)。如何将4个多维数组合并为1个多维

依我之见:

foreach ($rows2 as $msgs2) { 
$arraynew = array_merge($arraynew, array('cost' => $msgs2['vivod'], 'date' => $msgs2['date'], 'type' => '1')); 
} 

foreach ($rows3 as $msgs3) { 
$arraynew = array_merge($arraynew, array('cost' => $msgs3['price'], 'date' => $msgs3['data'], 'type' => '2')); 
} 

foreach ($rows4 as $msgs4) { 
$arraynew = array_merge($arraynew, array('cost' => $msgs4['price'], 'date' => $msgs4['data'], 'type' => '3')); 
} 

foreach ($rows5 as $msgs5) { 
    $arraynew = array_merge($arraynew, array('cost' => $msgs5['cost'], 'date' => $msgs5['data'], 'type' => '4')); 
} 

但它不工作。

+0

你可以用在你的SQL,以获得相同的字段名称:'选择vivod AS价格从items'如果帮助。 – Progrock

+0

如果你在阵列合并中的数组中包装你的数组,你的array_merge应该可以工作。不过,我不建议使用'array_merge'将一个附加元素添加到数组末尾,而是使用:'$ array [] = $ var;'。 – Progrock

+0

当你说它不起作用时,说出它在做什么以及它与你期望的有什么不同是很有用的。如果可能的话,举一个你想要的结果的例子。 – Progrock

回答

0
<?php 

$foos = [ 
    ['vivod' => '11', 'date' => '20140112'], 
    ['vivod' => '23', 'date' => '20140113'] 
]; 
$bars = [ 
    ['price' => '29', 'date' => '20171201'], 
    ['price' => '31', 'date' => '20170102'] 
]; 

$result = array(); 

foreach ($foos as $foo) { 
    $result[] = array('cost' => $foo['vivod'], 'date' => $foo['date'], 'type' => '1'); 
} 

foreach ($bars as $bar) { 
    $result[] = array('cost' => $bar['price'], 'date' => $bar['date'], 'type' => '2'); 
} 

var_export($result); 

输出:

array (
    0 => 
    array (
    'cost' => '11', 
    'date' => '20140112', 
    'type' => '1', 
), 
    1 => 
    array (
    'cost' => '23', 
    'date' => '20140113', 
    'type' => '1', 
), 
    2 => 
    array (
    'cost' => '29', 
    'date' => '20171201', 
    'type' => '2', 
), 
    3 => 
    array (
    'cost' => '31', 
    'date' => '20170102', 
    'type' => '2', 
), 
) 
+0

$ result = []; - 在[]发誓,崩溃PHP。 –

+0

您必须使用旧版本的Php(<5.4)。将该行替换为'$ result = array();'。 – Progrock

0

你所寻找的是array_merge_recursive

<?php 
$ar1 = array("color" => array("favorite" => "red"), 5); 
$ar2 = array(10, "color" => array("favorite" => "green", "blue")); 
$result = array_merge_recursive($ar1, $ar2); 
print_r($result); 
?> 

输出

Array 
(
    [color] => Array 
     (
      [favorite] => Array 
       (
        [0] => red 
        [1] => green 
       ) 

      [0] => blue 
     ) 

    [0] => 5 
    [1] => 10 
) 
0

使用array_reduce($array, 'array_merge', array())

例子:

$a = array(array(1, 2, 3), array(4, 5, 6),array(7, 8, 9),array(10, 11, 12)); 
$result = array_reduce($a, 'array_merge', array());`