php合并多维数组子集的一个问题
比如一个多维数组
<code>$arr = array( '0'=>array('1','2'), '1'=>array('2','3'), '2'=>array('3','4'), '3'=>array('4','5'), '4'=>array('5','6'), ) </code>
我要合并$arr的所有子集数组变成一个新的数组
<code>$new_arr = array('1','2','2','3','3','4','4','5','5','6'); </code>
最快的方法是什么
回复内容:
比如一个多维数组
<code>$arr = array( '0'=>array('1','2'), '1'=>array('2','3'), '2'=>array('3','4'), '3'=>array('4','5'), '4'=>array('5','6'), ) </code>
我要合并$arr的所有子集数组变成一个新的数组
<code>$new_arr = array('1','2','2','3','3','4','4','5','5','6'); </code>
最快的方法是什么
array_walk
版一号代码:
<code>$res = array(); array_walk($arr, function($item, $key) use (&$res) {$res = array_merge($res, $item);}); </code>
array_walk_recursive
版二号代码:
<code>$res = array(); array_walk_recursive($arr, function($item, $key) use (&$res) {$res[] = $item;}); </code>
优美的写法需要PHP版本的支持,如果不支持的话就把匿名函数和use
改成普通函数和global
的形式就好了。
补充答案:
foreach
循环普通版三号代码:
<code>$res = array(); foreach($arr as $item) {$res = array_merge($res, $item);} </code>
double foreach
嵌套循环普通版四号代码:
见 @thbourlove 的答案。
既然题主强调了一下时间的话那我就认真做一个测评好了,为了增加可比性我又写了一个普通版用循环的第三版作为对比代码,通过测试得到四组代码在不同数组长度的情况下所消耗的时间的一个表:
array_walk |
array_walk_recursive |
foreach |
double foreach |
|
500 | 0.12 | 0.003 | 0.067 | 0.003 |
100 | 0.45 | 0.006 | 0.331 | 0.003 |
1500 | 1.7 | 0.005 | 1.523 | 0.003 |
2000 | 3.38 | 0.005 | 2.092 | 0.003 |
2500 | 6.16 | 0.008 | 4.126 | 0.004 |
3000 | 10.15 | 0.010 | 6.258 | 0.005 |
*注1:表格左侧为数组的长度,默认算的是一级数组,例如题目中的数组长度为5。每个二级数组的长度统一为题目示例中的2。
*注2:表格中的数据默认单位为秒
*注3:本来其实测试数据为100000长度的数组的,结果array_walk
花了204s,我就放弃那么长了。
*注4:double foreach
的代码参见 @thbourlove 的答案,另外此算法的运算时间由于之前三者比较的数据已经不存在了,所以我重新找了一组规格相同的数据和第二种算法做了同期测试,并根据两组数据之间的关系得到了表格现在的数据。
通过以上数据可以得出,性能方面的话还是 @thbourlove 的嵌套循环是最高的,不过个人是代码美观控,所以还是比较偏爱第二种。
通过以上数据可以得出三种方法中array_walk_recursive
方法无疑是最快的。
array_walk_recursive
的低版本兼容写法我在这里补充一下:
<code>$res = array(); function merge($item, $key) { global $res; $res[] = $item } array_walk_recursive($arr, 'merge'); </code>
至于修改后的代码的效率测试我就不在这里多做了,相比最终得到的结果应该也是一样的。
本来要踩一下 @怡红公子 的答案的,结果发现自己声望不够,好吧,只好默默的答题了。。
其实认真分析一下 @怡红公子 答案里的那个benchmark表就看出来了,明显1号方案和3号方案的算法复杂度是O(mn^2),而2号方案的复杂度只有O(mn)。其中,m为哈希表内每个列表的长度,n为哈希表的长度。
是什么导致了这样的差距呢?再仔细看一眼代码,就会发现1号方案和3号方案同时出现了一个函数array_merge
。这货到底做了什么呢?
其实每次array_merge
操作都会把参数里的两个array合并,并且生成一个新的array并为其分配内存。这个操作的复杂度为O(mn),而$res[] = $item
这样一个往array里append的复杂度只有O(1),累积起来只有O(m)。所以benchmark的结果就可以理解了。
最后大家可以试试下面这段代码:
<code>$res = []; foreach ($arr as $item) { foreach ($item as $value) { $res[] = $item; } } </code>
理论上是一定比array_walk_recursive,具体我没怎么测,你们可以试试。
PS:array_walk
系列函数(包括array_walk
array_map
array_filter
……)我印象里都是比foreach要慢的,至少在php5.4.6上我实测如此。欢迎大家拍砖。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
