September 22

Multidimensional to nested array

Let us take an example to demonstrate purpose of this function. There is a database table that holds visit count data of web site. It has page, visit_time and visitor_ip columns. Following MySQL query shows visit count per page per day:

Result is following data set:

pagevisit_datecnt
/home2015-11-111312
/about2015-11-114543
/contact-us2015-11-113131
/home2015-11-121233
/about2015-11-124324
/contact-us2015-11-125435

This is transformed to PHP array:

This data structure is inconvenient if you try to retrieve visit count for page at particular date. You have to loop throughout entire array and ask if page and visit_date have specified values. Nested array is more convenient in this situation because it provides lookup direct by keys:

Multidimensional array can be transformed do nested using following function: