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:


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: