PHP多维数组:用两个值的串联替换所有键
我在PHP中有一个多维数组,其中外部数组包含数千个项目,其中每个项目都是一个数组本身,其值分别为 key1, key2和 count:
I have a multidimensional array in PHP, where the outer array contains several thousands items and each item inside is an array itself with the values "key1", "key2" and "count":
myExistingArray (size=99999 VERY BIG)
public 0 =>
array (size=3)
'key1' => string '15504'
'key2' => string '20'
'count' => string '1'
public 1 =>
array (size=3)
'key1' => string '15508' (length=5)
'key2' => string '20' (length=2)
'count' => string '2' (length=1)
public 2 =>
array (size=3)
'key1' => string '15510' (length=5)
'key2' => string '20' (length=2)
'count' => string '5' (length=1)
....many more similar items
我想将其转换为一个非常简单的数组,其中 key1和 key中的前一个值被连接为一个新的键,该键指向相应的 count值,如下所示:
I want to transform this into a very simple array, where the former values from "key1" and "key" are concatenated to be a new key that points to the corressponding "count" value like so:
myNewArray (size=99999 VERY BIG)
<key1>_<key2> => <count>
15504_20 => string '1' (length=1)
15508_20 => string '2' (length=1)
15510_20 => string '5' (length=1)
性能对我来说很重要,因为外部数组有多个一千个项目。 PHP中有快速方法吗?我唯一得到的只是一个简单的迭代,但这对我来说似乎很慢:
Performance is very important for me since the outer array has several thousand items. Is there a fast method in PHP? The only thing I got was a simple iteration, but this seems to slow for me:
// works but I am looking for a faster version
$myNewArray = array();
foreach ($myExistingArray as $item) {
$myNewArray [$item["key1"]."_".$item["key1"]]=$item["count"];
}
编辑/基本问题
有些人正确地补充说,我当前的解决方案已经在O(n)中,并提到PHP中没有内置函数可以加快此过程。
Some people rightfully added that my current solution is already in O(n) and mentioned that there is no built-in function in PHP to speed this up.
我从mysql数据库查询中获得 myExistingArray。我基本上有工作对象,并想按其状态和event_id将它们分组。查询与此类似:
I get "myExistingArray" from a mysql database query. I basically have job objects and want to group them by their status and their event_id. The query similiar to this:
select count(job.id) as count, job.status as key1, job.event_id as key2
from job
group by job.status, job.event_id
I希望重新排列键,以便以后可以轻松访问具有特定状态的特定事件的作业计数。
I want to rearrange the keys so that later I can easily access the count of jobs for a certain event with a certain status.
通常,您会寻找 array_walk
或 array_map
函数可用于转换PHP中的数组,但不幸的是,它们都不可以更改要转换的数组的键。 array_walk
将保留密钥,但不会更改它们。因此,可悲的是,没有,没有内置功能可以完成您要问的事情。
Ordinarily, you'd be looking for either the array_walk
or maybe the array_map
function to transform arrays in PHP, but unfortunately neither of them can alter the key of the array that you want to transform. array_walk
will preserve the keys, but won't alter them. So sadly, no, there's no built in function to do what you're asking.