note 55852 added to ref.array
| From: | DomenicDenicola at osu1 dot php dot net | Date: | Mon, 15 Aug 2005 18:49:23 +0000 |
| Subject: | note 55852 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-93690@lists.php.net to get a copy of this message | ||
Another JavaScript conversion, this time to objects instead of arrays. They can be accessed the same
way, but are declared much shorter, so it saves some download time for your users:
<?
function PhpArrayToJsObject($array, $objName)
{
return 'var ' . $objName . ' = ' . PhpArrayToJsObject_Recurse($array) .
";\n";
}
function PhpArrayToJsObject_Recurse($array)
{
// Base case of recursion: when the passed value is not a PHP array, just output it (in quotes).
if(! is_array($array) )
{
// Handle null specially: otherwise it becomes "".
if ($array === null)
{
return 'null';
}
return '"' . $array . '"';
}
// Open this JS object.
$retVal = "{";
// Output all key/value pairs as "$key" : $value
// * Output a JS object (using recursion), if $value is a PHP array.
// * Output the value in quotes, if $value is not an array (see above).
$first = true;
foreach($array as $key => $value)
{
// Add a comma before all but the first pair.
if (! $first )
{
$retVal .= ', ';
}
$first = false;
// Quote $key if it's a string.
if (is_string($key) )
{
$key = '"' . $key . '"';
}
$retVal .= $key . ' : ' . PhpArrayToJsObject_Recurse($value);
}
// Close and return the JS object.
return $retVal . "}";
}
?>
Difference from previous function: null values are no longer "" in the object, they are
JavaScript null.
So for example:
<?
$theArray = array("A" => array("a", "b", "c" =>
array("x")), "B" => "y");
echo PhpArrayToJsObject($theArray, "myArray");
?>
Gives:
var myArray = {"A" : {0 : "a", 1 : "b", "c" : {0 :
"x"}}, "B" : "y"};
You can still access them just like arrays, with myArray["A"][0] or
myArray["A"]["c"][0] or whatever. Just shrinks your pages.
----
Manual Page -- http://www.php.net/manual/en/ref.array.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+55852
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+55852&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+55852&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+55852&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+55852&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+55852&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+55852&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+55852&report=yes
Search -- http://master.php.net/manage/user-notes.php