Last active
August 29, 2015 14:19
-
-
Save schmohlio/44b36146a54800334e77 to your computer and use it in GitHub Desktop.
flatten nested array, where each level of the the tree represents a different category to search by, and preserve traversal metadata.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @keys n-length list of "labels", where the @key[i] is the category label of the ith level of @dat | |
* @dat a nested associative array, tree-like, with n+1 levels, where 1..n levels of the tree represent categories | |
* and the n+1 level is the actual request data. | |
* returns: list of associative arrays, each representing rows to be inserted into database. | |
* | |
* flattens nested array into a list of "rows", where the |rows| == |leaves in tree|. | |
* each "row" contains the data within the leaves, plus n additional key-value pairs represented by | |
* label => category (i.e. [...country => 'US', type => 'tablet'] when @keys = ['country', 'type'], and @dat has n+1==3 levels.) | |
**/ | |
public static function nestedArrayToListOfArrays($keys, $dat) { | |
if (!isset($keys)) { | |
return $dat; | |
} | |
$data = array(); | |
array_push($data, array( | |
'data' => $dat //$this->to_array() | |
)); | |
while (count($keys)>0) { | |
$new_data = []; | |
$key = array_shift($keys); | |
foreach($data as $num => $row) { | |
foreach($row['data'] as $k => $v) { | |
$new_row = $row; | |
$new_row[$key] = $k; | |
$new_row['data'] = $v; | |
array_push($new_data, $new_row); | |
} | |
$data = $new_data; | |
} | |
} | |
return $data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment