note 80616 deleted from ref.array by cmb
| From: | cmb@php.net | Date: | Tue, 27 Sep 2016 23:55:41 +0000 |
| Subject: | note 80616 deleted from ref.array by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-206689@lists.php.net to get a copy of this message | ||
Note Submitter: Jck_true (leave out the '_' at gmail dot com)
----
A usefull function that returns a flat array.
I use it in a template system. Let the user pass a multidimensional array. Convert it using my
function. Then use
<?php
$array = flatten($array,'','{$','}','->');
echo str_replace(array_keys($array),array_values($array),$template)
/**
* Flattens out an multidimension array
* Using the last parameters you can define the new key based on the old path.
* @param array $array A multidimension array
* @param string $prefix Internal perfix parameter - leave empty.
* @param string $start_string What string should start the final array key?
* @param string $end_string What string should end the final array key?
* @param string $seperator The string that should seperate the piecies in final array key path
* @return array Returns the flat array
*/
function flatten($array, $start_string= '{$',$end_string=
'}',$seperator='->',$prefix="") {
$return = array();
foreach($array as $key=>$value) {
if (is_array($value)) {
$return = array_merge($return, Parser_method_replace::flatten($value,
$prefix.$key.$seperator,$start_string,$end_string,$seperator));
} else
$return [$start_string.$prefix.$key.$end_string] = $value;
}
return $return;
}
}
?>
Example:
$template = 'My string with replacement {$test->subkey}';
{$test->subkey} will get replaced with $array['test']['subkey']