note 29542 deleted from ref.array by sniper
| From: | sniper@php.net | Date: | Sat, 18 Oct 2003 18:02:02 +0000 |
| Subject: | note 29542 deleted from ref.array by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-58828@lists.php.net to get a copy of this message | ||
Note Submitter: josh NO at SPAM mirtec dot net
----
Instant JavaScript array from PHP array (any combination of associative / numeric sub-arrays):
function arrayToJS ($theArray, $jsArrayName)
{
$jsArrayString = $jsArrayName . " = new Array ();\n";
foreach ($theArray as $key => $val)
{
if (is_numeric ($key))
{
$jsElement = $key;
}
else
{
$jsElement = '\'' . $key . '\'';
}
if (is_array ($val))
{
$jsArrayString .= arrayToJS ($val, $jsArrayName . '[' . $jsElement .
']');
}
else
{
if (is_numeric ($val))
{
$jsValue = $val;
}
else
{
$jsValue = '\'' . $val . '\'';
}
$jsArrayString .= $jsArrayName . '[' . $jsElement . '] = ' .
$jsValue . ";\n";
}
}
return $jsArrayString;
}
//----------------usage------------------//
echo '<script language="JavaScript" type="text/javascript">';
echo arrayToJS ($myArray, 'myJSArray');
echo '</script>';
// for some reason the PHP site keeps scrambling my indentation .. :(