热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

数组合并到多维数组。-arraymergingintomultidimensionalarray

Ineedawaytomerge我需要一个合并的方法。Array([0]>Array([event_id]>1[t

I need a way to merge

我需要一个合并的方法。

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'
     )
 )

into:

成:

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'
     )
)

So the new array is grouped by the day key and if the values are different between the merged arrays then the merged value becomes an array.

因此,新的数组按日键分组,如果合并数组中的值不同,则合并后的值就会变成一个数组。

3 个解决方案

#1


2  

This should work.

这应该工作。

$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  

I can't think of a built in function that will do this for you. I think you will have to loop through, group the events by day, then loop through the group and convert to the correct output format.

我想不出一个内建函数能帮到你。我认为您必须循环遍历,按天对事件进行分组,然后循环遍历该组,并将其转换为正确的输出格式。

E.g.

如。

This does not take into account the fact that the days may not always be in the same case, and also does not order the events by time, which may also be required.

这并没有考虑到这样一个事实,即天不一定总是在同一种情况下,而且也不按时间顺序排列事件,这也可能是必需的。

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));

#3


2  

I 'd propose this method which is fully generic and extensible:

我建议这个方法是完全通用和可扩展的:

// 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);

Advantages:

优点:

  1. There is only one magic value (the string "day"), which can be easily made into a variable and the whole thing factored out into a function (so you could reuse this function to perform the same transformation over any other property you might want to).
  2. 只有一个神奇的值(字符串“day”),它可以很容易地变成一个变量,整个东西可以分解成一个函数(因此您可以重用这个函数,对任何其他您可能想要的属性执行相同的转换)。
  3. Should be plenty fast due to using the built-in functions array_reduce and array_map instead of manually doing the same work in PHP.
  4. 由于使用内置函数array_reduce和array_map而不是在PHP中手工执行相同的工作,所以应该会非常快。

Disadvantages:

缺点:

  1. Requires PHP >= 5.3 due to the use of anonymous functions and the third parameter of array_reduce.
  2. 由于使用匿名函数和array_reduce的第三个参数,需要PHP >= 5.3。
  3. Not very easy to understand (although code that does this kind of data massaging won't be too easy to visualize in any case).
  4. 理解起来并不容易(尽管做这种数据处理的代码在任何情况下都不太容易可视化)。

推荐阅读
  • 生成式对抗网络模型综述摘要生成式对抗网络模型(GAN)是基于深度学习的一种强大的生成模型,可以应用于计算机视觉、自然语言处理、半监督学习等重要领域。生成式对抗网络 ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • IhaveconfiguredanactionforaremotenotificationwhenitarrivestomyiOsapp.Iwanttwodiff ... [详细]
  • Linux重启网络命令实例及关机和重启示例教程
    本文介绍了Linux系统中重启网络命令的实例,以及使用不同方式关机和重启系统的示例教程。包括使用图形界面和控制台访问系统的方法,以及使用shutdown命令进行系统关机和重启的句法和用法。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • sklearn数据集库中的常用数据集类型介绍
    本文介绍了sklearn数据集库中常用的数据集类型,包括玩具数据集和样本生成器。其中详细介绍了波士顿房价数据集,包含了波士顿506处房屋的13种不同特征以及房屋价格,适用于回归任务。 ... [详细]
  • 用Vue实现的Demo商品管理效果图及实现代码
    本文介绍了一个使用Vue实现的Demo商品管理的效果图及实现代码。 ... [详细]
  • 本文介绍了利用ARMA模型对平稳非白噪声序列进行建模的步骤及代码实现。首先对观察值序列进行样本自相关系数和样本偏自相关系数的计算,然后根据这些系数的性质选择适当的ARMA模型进行拟合,并估计模型中的位置参数。接着进行模型的有效性检验,如果不通过则重新选择模型再拟合,如果通过则进行模型优化。最后利用拟合模型预测序列的未来走势。文章还介绍了绘制时序图、平稳性检验、白噪声检验、确定ARMA阶数和预测未来走势的代码实现。 ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • 本文讨论了使用差分约束系统求解House Man跳跃问题的思路与方法。给定一组不同高度,要求从最低点跳跃到最高点,每次跳跃的距离不超过D,并且不能改变给定的顺序。通过建立差分约束系统,将问题转化为图的建立和查询距离的问题。文章详细介绍了建立约束条件的方法,并使用SPFA算法判环并输出结果。同时还讨论了建边方向和跳跃顺序的关系。 ... [详细]
  • HDFS2.x新特性
    一、集群间数据拷贝scp实现两个远程主机之间的文件复制scp-rhello.txtroothadoop103:useratguiguhello.txt推pushscp-rr ... [详细]
  • 模板引擎StringTemplate的使用方法和特点
    本文介绍了模板引擎StringTemplate的使用方法和特点,包括强制Model和View的分离、Lazy-Evaluation、Recursive enable等。同时,还介绍了StringTemplate语法中的属性和普通字符的使用方法,并提供了向模板填充属性的示例代码。 ... [详细]
  • 本文介绍了Codeforces Round #321 (Div. 2)比赛中的问题Kefa and Dishes,通过状压和spfa算法解决了这个问题。给定一个有向图,求在不超过m步的情况下,能获得的最大权值和。点不能重复走。文章详细介绍了问题的题意、解题思路和代码实现。 ... [详细]
  • Ihaveaworkfolderdirectory.我有一个工作文件夹目录。holderDir.glob(*)>holder[ProjectOne, ... [详细]
author-avatar
劈腿年代shui还相信真爱
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有