如何合并这两个数组

时间:2016-05-31 07:38:08

标签: php arrays multidimensional-array

我有一个$ distNames数组,其中包含地区名称。

$distNames = array(0 => "North",1 => "West",2 => "South",3 => "East");

我有另一个名为$ rdata的数组,其中包含一个区的计数。

$rdata = array("North" => array("rural" => 2, "urban" => 0), 
   "East" => array("rural" => 1, "urban" => 0));

我有另一个名为$ udata的数组,其中包含一个区的计数。

$rdata = array("South" => array("rural" => 0, "urban" => 1), 
    "East" => array("rural" => 0, "urban" => 2));

我必须根据区域数组合并$ rdata和$ udata。预期的结果将是这样的。

$data = array(
      'North' => array('rural' =>2,'urban' => 0,'total' => 3),
      'South' => array('rural' =>0,'urban' => 1,'total' => 1),
      'West' => array('rural' =>0,'urban' => 0,'total' => 0),
      'East' => array('rural' =>1,'urban' => 2,'total' => 3)
    );

总价值应该是农村和城市的总和。任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:0)

$data = array(); 
for ($i = 0; $i < count($distNames); $i++) {
    $tempArr = array();
    $direction = $distNames[$i];
    $data[$direction] = array(
        'rural' => isset($rdata[$direction]['rural']) ? $rdata[$direction]['rural'] : 0,
        'urban' => isset($udata[$direction]['urban']) ? $udata[$direction]['urban'] : 0,
        'total' => $rdata[$direction]['rural'] + $udata[$direction]['urban']
    ); 
}

echo "<pre>";
print_r($data);

这将适用于您定义的数组名称,即$ data,$ distNames,$ rdata和$ udata

答案 1 :(得分:0)

Hii尝试使用它。

<?php
$distNames = array(0 => "North",1 => "West",2 => "South",3 => "East");
$rdata = array("North" => array("rural" => 2,"urban" => 0),"East" => array("rural" => 1,"urban" => 0));
$udata = array("South" => array("rural" => 0,"urban" => 1),"East" => array("rural" => 0,"urban" => 2));

    $data = array();
foreach($distNames as $drname){
   $data[$drname]['rural'] = ($rdata[$drname]['rural'] + $udata[$drname]['rural']);
   $data[$drname]['urban'] = ($rdata[$drname]['urban'] + $udata[$drname]['urban']);
   $data[$drname]['total'] = ($new[$drname]['urban'] + $new[$drname]['rural']);

}
echo "<pre>";echo "<pre>";print_r($data);

答案 2 :(得分:0)

我这样做了

$data = array();
    $total = 0;
    for ($i = 0; $i < count($distNames); $i++) {
      $direction = $distNames[$i];
      if(isset($tlRuralNw[$direction]) && isset($tlUrbanNw[$direction])) {
        $total = $tlRuralNw[$direction] + $tlUrbanNw[$direction];
      }
      elseif(isset($tlRuralNw[$direction]) && !isset($tlUrbanNw[$direction])) {
        $total = $tlRuralNw[$direction];
      }
      elseif(!isset($tlRuralNw[$direction]) && isset($tlUrbanNw[$direction])) {
        $total = $tlUrbanNw[$direction];
      }
      elseif(!isset($tlRuralNw[$direction]) && !isset($tlUrbanNw[$direction])) {
        $total = 0;
      }
      $data[$direction] = array(
        'rural' => isset($tlRuralNw[$direction])?$tlRuralNw[$direction]:0,
        'urban' => isset($tlUrbanNw[$direction])?$tlUrbanNw[$direction]:0,
        'total' => $total
      );
    }

谢谢大家的帮助。