note 80065 deleted from language.variables.variable by cmb
| From: | cmb@php.net | Date: | Sun, 12 Jan 2020 08:31:26 +0000 |
| Subject: | note 80065 deleted from language.variables.variable by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-213861@lists.php.net to get a copy of this message | ||
Note Submitter: craigmorey at gmail dot com
----
For a long time I've been trying to use variable variables to figure out how to store and
retrieve multi-dimensional arrays in a MySQL dbase. For instance, a config setting stored in a
complex array might resemble the below:
<?php
$config['modules']['module_events']['settings']['template']['name']
= 'List Page'; ?>
The most obvious way for storing this info in a dbase (discounting XML/JSON) is to store a
"path" (of the nesting) and a "value" in a database record:
'modules,module_events,settings,template,name' = 'List Page'
But storing it is only part of the problem. PHP variable variables are no use to try and interpret
string representations of arrays, eg it will see the string representation of a nested array such as
config['modules']['module_events'] as a single variable called
'config[modules][module_events]', so loops that parse the "path" into a variable
variable don't help.
So here is a little function that parses an array of "paths" and "value" strings
(eg from a dbase) into a multi-dimensional nested array.
<?php
function multiArrayMe($input_array) {
$output_array = array();
# common sense check
if (!is_array($input_array)) {
return false;
}
# loop through the array of "path"=>"value"
foreach ($input_array AS $key1 => $val1) {
# explode the path to find the list of nested keys
$temp1 = explode(',',$key1);
# if this path isn't an array, skip this cycle
if (!is_array($temp1)) {
continue;
}
# reverse sort the keys so we'll start building from
# the bottom, not the top
krsort($temp1);
# start with the temporary array off with the end value
$temp2 = $val1;
# loop through the nested keys
foreach($temp1 AS $val2) {
# if this nested key has no name,
# (and isn't "0") skip this cycle
if ($val2===false) {
continue;
}
#Â gradually build up the this temporary nested array
# from the leaf, working up the branches to the trunk
$temp2 = array($val2 => $temp2);
}
# for this cycle, dump this bucketful of data into the bathtub
$output_array = array_merge_recursive($output_array,$temp2);
}
return $output_array;
}
?>