PHP - translating an array to a map of arrays -


i have array of objects - results of query.

it looks this: j - number of rows returned table

result[j]->date, result[j]->user, result[j]->count 

the pk of table date+user, meaning can have rows:

1.1.2016 user1 5 1.1.2016 user2 8 5.1.2016 user1 4 

for purpose need create map have number of elements = number of different dates in previous array, that:

map[j=datex] -> array consist of pairs (user+count) many have have date. 

meaning on date 1.1.2016 have 2 objects - (user1, 5) , (user2, 8) , on date 5.1.2016 1 pair (user1, 4) there structure in php can me create "map" there in java example?

use array_map. iterate on every object in array , add them new array same key (date). results objects same date in 1 array.

$map = array(); // new mapped array array_map(function($obj) use (&$map){     $map[$obj->date][] = $obj; }, $arr); 

test

$obj1 = new stdclass(); $obj1->date = '1.1.2016'; $obj1->user = 'user1'; $obj1->count = 5;  $obj2 = clone $obj1; $obj2->user = 'user2'; $obj2->count = 8;  $obj3 = clone $obj1; $obj3->date = '5.1.2016'; $obj3->count = 4;  $arr = array($obj1, $obj2, $obj3);  $map = array(); array_map(function($obj) use (&$map){     $map[$obj->date][] = $obj; }, $arr);  print_r($map); 

output

array (     [1.1.2016] => array         (             [0] => stdclass object                 (                     [date] => 1.1.2016                     [user] => user1                     [count] => 5                 )              [1] => stdclass object                 (                     [date] => 1.1.2016                     [user] => user2                     [count] => 8                 )          )      [5.1.2016] => array         (             [0] => stdclass object                 (                     [date] => 5.1.2016                     [user] => user1                     [count] => 4                 )          )  ) 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -