WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
PHP Web Logs (BLogs)
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Submit Site
Forex Trading Online forex trading platform

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : PHP Array to Javascript Object
Categories : PHP, Arrays, Java Script Click here to Update Your Picture
Sumit Agarwal
Date : Nov 17th 2007
Grade : 5 of 5 (graded 1 times)
Viewed : 1607
File : No file for this code example.
Images : No Images for this code example.
Search : More code by Sumit Agarwal
Action : Grade This Code Example
Tools : My Examples List

  Submit your own code examples 
 

This is a function to convert a PHP Array to a Javascript Object variable. The object variable can be accessed like any other object variable. You can traverse the object using the for...in loop.

The first argument to the function is the php array to be converted. The second argument is the name for the javascript object. The third parameter should not be set directly.

<?php

function arrayToJSObject($array, $varname, $sub = false ) {
   
$jsarray = $sub ? $varname . "{" : $varname . " = {\n";
   
$varname = "\t$varname";
   
reset ($array);

   
// Loop through each element of the array
   
while (list($key, $value) = each($array)) {
       
$jskey = "'" . $key . "' : ";
       
        if (
is_array($value)) {
           
// Multi Dimensional Array
           
$temp[] = arrayToJSObject($value, $jskey, true);
        } else {
            if (
is_numeric($value)) {
               
$jskey .= "$value";
            } elseif (
is_bool($value)) {
               
$jskey .= ($value ? 'true' : 'false') . "";
            } elseif (
$value === NULL) {
               
$jskey .= "null";
            } else {
                static
$pattern = array("\\", "'", "\r", "\n");
                static
$replace = array('\\', '\\\'', '\r', '\n');
               
$jskey .= "'" . str_replace($pattern, $replace, $value) . "'";
            }
           
$temp[] = $jskey;
        }
    }
   
$jsarray .= implode(', ', $temp);

   
$jsarray .= "}\n";
    return
$jsarray;
}

$fruits = array(
    array(
'id' => 1, 'name' => 'Apple', 'color' => 'Red'),
    array(
'id' => 2, 'name' => 'Orange', 'color' => 'Orange'),
    array(
'id' => 3, 'name' => 'Mango', 'color' => 'Yellow')
);
$random = array(
    array(
1 => 1, 'value' => 25.5, 'spl' => array(
           
'dblquote' => 'Test " Test',
           
'sglquote' => "Test ' Test",
           
'newline'  => "Test \n Test"
       
)
    ),
    array(
'a' => 2, 'value' => true),
    array(
"name" => 3, 'value' => "Sumit")
);

?>
<html>
<head>
<title>PHP Array to JS Object</title>
</head>
<body>
<script type="text/javascript">
<!--
<?php
echo arrayToJSObject($fruits, 'fruits');
echo
arrayToJSObject($random, 'random');

?>
alert(fruits);
alert(random[0].spl.newline);
alert(random[2].value);
//-->
</script>
</body>
</html>



Array values from javascript to php
Categories : PHP, Java Script, Arrays
enhanced date picker with jcript checking for a dynamic date input
Categories : PHP, Java Script, Date Time, Calendar, Arrays
Dynamic Loading of XML array data into ComboBox and Display XML data using PHP + DOM + Javascript.
Categories : PHP, Java Script, DOM XML, XML, Arrays
Tag content retrieval from websites with preg_match
Categories : PHP, Regexps, Arrays, HTML and PHP
Zephyr: AJAX Based Framework for PHP5 Developers
Categories : PHP, AJAX, Frameworks, Java Script, Web Applications
clearing variables in php3
Categories : Variables, Arrays, PHP
Create HTML forms dynamicly using Javascript & PHP
Categories : PHP, PHP Classes, Java Script
Linked comboboxes with php-mysql & javascript
Categories : PHP, Java Script, Databases, MySQL
Weighted Random - Random Scripts usually chose one out of each item, and each item have an equal chance to be chosen. But what if you want an item to be chosed more frequently than other?
Categories : PHP, Math., Arrays
The toll booth
Categories : PHP, Java Script, Filesystem
MD5 secured login
Categories : PHP, Java Script, Authentication, Security
Display list of files within current and subdirectories (recursively) showing each file as an anchored link and each directory as a category header.
Categories : Filesystem, Directories, Arrays, PHP
Pull Down Surfing - Surf on Change
Categories : Java Script, MySQL, HTML and PHP, PHP, Databases
Array Insertion
Categories : PHP, PHP Classes, Arrays
PHP Script to find url links in a page
Categories : PHP, URLs, Regexps, Arrays