note 55852 deleted from ref.array by levim

From: Date: Tue, 06 May 2014 22:01:54 +0000
Subject: note 55852 deleted from ref.array by levim
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-199446@lists.php.net to get a copy of this message
Note Submitter: Domenic Denicola ---- 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.

« previous php.notes (#199446) next »