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
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)
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"];
}
EDIT / Underlying problem
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.
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 want to rearrange the keys so that later I can easily access the count of jobs for a certain event with a certain status.
SELECT CONCAT(key1, '_', key2) as key, count [...]then unset the current row in php foreach to gain memory :)