<?php
/**
* Make sure the function is not already defined.
*
*/
if ( ! function_exists('array_to_php') )
{
/**
* Builds the php code (keyed, escaped and nested) for a php array for caching or data storage
*
* @param array $a The array of data to translate
* @param bool $self_call Is this function being called by itself?
* @param integer $nest_level The current nesting level of the function
*
* @author Dean Newman <webmaster@auscoder.com>
* @example echo '<pre>' . array_to_php( array(1 => array(1,2,3),2,3,4) ) . '</pre>';
* @return string The final result (php code)
*/
function array_to_php ( $a, $self_call = false, $nest_level = 1 )
{
// Set initial string
$str = 'array(';
// Declare key counter
$i = 0;
// Reset to start of array
reset ( $a );
// Increase nesting level on self-call
if ( $self_call )
{
$nest_level++;
}
// Assign the tabs for each level in
$tab = '';
for ( $i = 0 ; $i < $nest_level ; $i++ )
{
$tab .= "\t";
}
// Loop though the array building php code
$i = 0;
while ( list ( $key, $value ) = @each ( $a ) )
{
// Check if the value is an array
if ( is_array ( $value ) )
{
// The value is an array, do a self-call
$str .= "\n$tab'$key' => " . array_to_php($value, true, $nest_level);
}
else
{
// The value is not an array, do escaping
$key = str_replace('\\', '\\\\', $key);
$key = str_replace('\'', '\\\'', $key);
$value = str_replace('\\', '\\\\', $value);
$value = str_replace('\'', '\\\'', $value);
// Generate the code
$str .= "\n$tab'$key' => '$value'";
}
// Seperator
if ( $i < (sizeof($a) - 1) )
{
$str .= ',';
}
// Increase counter
$i++;
}
// Ending bracket for self-call
if ( $self_call )
{
// 1 tab must be removed for clean code
$s_tab = substr ( $tab, 0, ( strlen ( $tab ) - 1 ) );
// Create array end bracket
$str .= "\n$s_tab)";
}
else
{
// End array as normal
$str .= "\n)";
}
// Return the generated php code
return $str;
}
}
?>