数组合并为多维数组

时间:2011-09-06 10:13:08

标签: php arrays

我需要一种合并方式

Array(
  [0] => Array
     (
      [event_id] => 1
      [time] => '21:00pm'
      [day] => 'Monday'
     )
  [1] => Array
    (
      [event_id] => 2
      [time] => '18:00pm'
      [day] => 'Monday'
     )
  [2] => Array
    (
      [event_id] => 3
      [time] => '21:00pm'
      [day] => 'Tuesday'
     )
 )

成:

Array (
  [0] => Array
      (
          [event_id] => Array
                (
                 [0] => 1
                 [1] => 2
                )
          [time] => Array
               (
                 [0] => '21:00pm'
                 [1] => '18:00pm'
                )
          [day] => 'Monday'
      )
   [1] => Array
     (
          [event_id] => 3
          [time] => '21:00pm'
          [day] => 'Tuesday'
     )
)

因此新数组按日键分组,如果合并数组之间的值不同,则合并后的值将变为数组。

3 个答案:

答案 0 :(得分:2)

我想不出一个能为你做这件事的内置功能。我认为你必须循环,按天分组事件,然后遍历组并转换为正确的输出格式。

E.g。

这并未考虑这样的事实:日期可能并非总是在同一个案例中,也不会按时间对事件进行排序,这也可能是必需的。

function convert_event_array ($array) {

  // Declare the arrays we will use
  $temp = array(
    // Declare the day keys, so they appear in the right order in the output
    'Monday'=>array(),
    'Tuesday'=>array(),
    'Wednesday'=>array(),
    'Thursday'=>array(),
    'Friday'=>array(),
    'Saturday'=>array(),
    'Sunday'=>array()
  );
  $out = array();

  // Put events into temp array, grouped by day
  foreach ($array as $event) $temp[$event['day']][] = array('event_id'=>$event['event_id'],'time'=>$event['event_id']);

  // Convert grouped array to the correct format
  foreach ($temp as $day => $events) if (count($events)) {
    $index = count($out);
    foreach ($events as $event) {
      $out[$index]['event_id'][] = $event['event_id'];
      $out[$index]['time'][] = $event['time'];
    }
    $out[$index]['day'] = $day;
  }

  return $out;

}

print_r(convert_event_array($myInputArry));

答案 1 :(得分:2)

这应该有用。

$output = getMergedArray($input); // $input is your sample array

function getMergedArray($input_array) {
  $output_array = array();
  foreach ($input_array as $key => $value) {
    $event_id = $value['event_id'];
    $time = $value['time'];
    $day = $value['day'];
    $day_id = getDay($output_array, $day);
    if (count($output_array) > 0 && $day_id >= 0) {
      if (!is_array($output_array[$day_id]['event_id'])) {
        $output_array[$day_id]['event_id'] = array($output_array[$day_id]['event_id']);
        $output_array[$day_id]['time'] = array($output_array[$day_id]['time']);
      }
      array_push($output_array[$day_id]['event_id'],$event_id);
      array_push($output_array[$day_id]['time'],$time);
    } else {
      $output_array[] = $value;
    }
  }
  return $output_array;
}

function getDay($output_array, $day) {
  if (count($output_array) > 0)
    foreach($output_array as $key => $value)
      if ($value['day'] == $day)
        return $key;

  return -1;
}

答案 2 :(得分:2)

我建议这种方法完全通用且可扩展:

// YOUR INPUT GOES HERE
$input = (...);

// Stage 1: group elements of the initial array into sub-arrays based on their 'day' key
$groupLambda = function($aggr, $val) {
                   $aggr[$val['day']][] = $val; return $aggr;
               };
$grouped = array_reduce($input, $groupLambda, array());

// Stage 2: for each "same day" group, make an array of values for each property
//          instead of an array of items with scalar properties
$coalesceLambda = function($group) {
                      $mapLambda = function($aggr, $val) {
                          foreach($val as $k => $v) {
                              if($k == 'day') continue;
                              $aggr[$k][] = $v; 
                          }
                          return $aggr;
                      };
                      return array_reduce($group, $mapLambda, array());
                  };
$coalesced = array_map($coalesceLambda, $grouped);

// Get the result
print_r($coalesced);

<强>优点:

  1. 只有一个魔术值(字符串“day”),它可以很容易地变成一个变量,整个事物被分解成一个函数(所以你可以重用这个函数来执行与任何其他属性相同的转换)你可能想要)。
  2. 由于使用内置函数array_reducearray_map而不是在PHP中手动执行相同的工作,因此应该足够快。
  3. <强>缺点:

    1. 由于使用了匿名函数和array_reduce的第三个参数,因此需要PHP&gt; = 5.3。
    2. 不是很容易理解(尽管执行此类数据按摩的代码在任何情况下都不会太容易可视化。)