Convert PHP Array to JavaScript Array

<?php
////////////////////////////////////////////////////////////////////////////////////////////
// Universal function used to convert array in PHP to array in Javascript. //
// The result will be in string, includes declaration in Javascript, as well as the value //
// assigned to array in Javascript. //
// The array can be associative, as well as multidimensional, as many multidimensions as //
// you wish. This funcation is particularily useful when the number of elements and level //
// of multidimension is unknown. //
// Parameter $sJS is the string to represent the name of array in JS as you wish. //
////////////////////////////////////////////////////////////////////////////////////////////

function arrayToJavascript($aPHP, $aJS) // This is to deal with first level of recursion.
{
$lenFirst = @count($aPHP); // "@" deals with PHP Error Massage.
if (0!=$lenFirst && is_array($aPHP)) // Test if this is valid array or if reached the end of array.
{
echo "var ".$aJS." = new Array(".$lenFirst.");\n"; // Declare first level of array.
foreach ($aPHP as $key => &$value)
{
if (is_numeric($key))
{
$arrayString = $aJS."[".$key."]"; // Javascript variable.
}
else
{
$arrayString = $aJS."['".$key."']"; // Javascript variable.
};
toJSrecur($arrayString, $aPHP[$key]);
};
}
else
{
echo "Input is not a valid PHP array.";
};
}

function toJSrecur($arrayJS, $element) // This is to deal with standard level of recursion.
{ $len = @count($element); // count() does cause the trouble when reach the end of array.
if (0!=$len && is_array($element))
{
echo $arrayJS." = new Array(".$len.");\n"; // Declare each level of array.
foreach ($element as $key => &$value)
{
if (is_numeric($key))
{
$newString = $arrayJS."[".$key."]"; // Javascript variable.
}
else
{
$newString = $arrayJS."['".$key."']"; // String, is to be used by the echo at next level.
};
toJSrecur($newString, $element[$key]);
};
}
else // Start to write into javascript array at end of each branch in the recursion.
{
if ($element)
{
if (is_numeric($element))
{
$eleValue = $element;
}
else // Sign "'" in Javascript does cause trouble. Escape is needed.
{
$eleValue = "'".str_replace("'", "\'", $element)."'";
};
}
else
{
$eleValue = "''";
};
echo $arrayJS." = ".$eleValue.";\n"; // Assign values when the branch reached the end.
};
}

?>

No comments:

Post a Comment

Labels