检索具有相同值的数组中的元素,并将它们分组以处理组

时间:2015-05-04 09:49:56

标签: php arrays

我有一个如下所示的数组

 $crops = array(
  0 => array(
      'crop_name' => 'Maize',
      'crop_variety_name' => 'Longe 10H',
      'weeks' => array(
          9  => 11.200,
          10 => 14.700,
          11 => 12.300,
          12 => 4.300,
          14 => 8.500,
          16 => 18.800,
          17 => 10.600,
          20 => 10.000,
          30 => 7.000
     )
 ),
  1 => array(
     'crop_name' => 'Maize',
     'crop_variety_name' => 'Longe 5',
     'weeks' => array(
          15 => 15.400,
          16 => 4.700,
          19 => 11.000,
          20 => 3.000,
          21 => 5.000,
          29 => 2.000
     )
 ),
  2 => array(
     'crop_name' => 'Maize',
     'crop_variety_name' => 'VP Max',
     'weeks' => array(
          9 => 6.800,
          10 => 8.000,
          14 => 3.000,
          15 => 6.800,
          17 => 4.300,
          18 => 7.400,
          20 => 5.900,
          21 => 2.400,
          22 => 2.800,
          23 => 5.400,
          24 => 3.900
     )
 ),
  3 => array(
     'crop_name' => 'Rice',
    'crop_variety_name' => 'Superica 2',
    'weeks' => array(
         18 => 6.600,
         19 => 11.500,
         20 => 8.300,
         21 => 10.100,
         24 => 2.800
    )
),
 4 => array(
    'crop_name' => 'Soya',
    'crop_variety_name' => 'Soya N1',
    'weeks' => array(
         20 => 3.000
    )
),
 5 => array(
    'crop_name' => 'Soya',
    'crop_variety_name' => 'Soya N3',
    'weeks' => array(
         10 => 5.9,
         11 => 12.800,
         12 => 5.100,
         15 => 4.000,
         19 => 4.000,
         31 => 3.100
     )
   )
);

不同的庄稼crop_name有一个或多个品种crop_variety_name。我想检索作物,例如`' crop_name' =>'玉米'无论他们的作物品种如何,然后检索周数组并在周数组中添加每个作物品种的所有值,这样我就有这样的数组

array(
    'Maize' => 195.2,
    'Rice' => 39.3
    'Soya' => 37.9)

其中键是crop_name,值是每个作物的crop_varieties的周数组中的值的总和。第一个数组可以包含任意数量的crop,crop_varieties和weeks数组可以包含任意数量的值。我怎么能这样做呢。对于作物名称我尝试了这个

   $crop_names = array();
          for($i = 0; $i < count($crops); $i++ ){
             array_push($crop_names, $crops[$i]['crop_name']);  
               }
               $crop_name = array_values(array_unique($crop_names));

这适用于crop_names但array_unique会导致数据丢失。

1 个答案:

答案 0 :(得分:1)

您的代码与您的要求不符。

  

我想检索作物,例如`&#39; crop_name&#39; =&gt;&#39;玉米&#39;无论他们的作物品种如何,然后检索周数组并在周数组中添加每个作物品种的所有值,这样我就有这样的数组

array(
    'Maize' => 195.2,
    'Rice' => 39.3
    'Soya' => 37.9)

这就是将上述要求转化为代码的方式:

$amounts = array();
foreach ($crops as $crop) {
    $name = $crop['crop_name'];
    if (! isset($amounts[$name])) {
        // This is the first time when this crop type is processed
        $amounts[$name] = 0;
    }
    // Add all the values in the week array regardless of varieties
    $amounts[$name] += array_sum($crop['weeks']);
}

// If you need the names in a separate list you can get it with array_keys()
$crop_names = array_keys($amounts);

请查看PHP手册的array functions部分以获取更多想法。