WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Poker Tournaments Poker Tournaments
Poker Guide for Developers Poker Guide for Developers
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
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 Resources
Web Development Content
Internet Security Software
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
פרייסז - הכח לקנות עובר לידיים שלך
Texas Holdem Poker Evangelists

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 3 times)
Viewed : 14620
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  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>



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
Array values from javascript to php
Categories : PHP, Java Script, Arrays
Local-to-user date and time display regardless of time zone or where the website's server is located
Categories : PHP, Date Time, HTML and PHP, Java Script
Single-file PHP news system with automatic folder structure creation
Categories : PHP, Filesystem, Arrays
Parsing html tags with php. Get an array from this function
Categories : PHP, HTML and PHP, Arrays, Tag Extractors
Takes an array and returns a string, suitable for inputing in an SQL statement
Categories : Arrays, Strings, PHP
Query2Report : Generating Html, Pdf and Csv Reports from SQL Query
Categories : PHP, PHP, HTML, PDF, Excel
Check for functional file links (broken Files)
Categories : PHP, Data Validation, FTP, Regexps, Arrays
Grab images from one or more URLs and save them to a specified local directory.
Categories : PHP, Filesystem, Strings, Arrays
How to Get a character array from a string
Categories : PHP, Strings, Arrays
PHP Dump in html format the contents of one array variable with a recursive list of the nested array variables inside.
Categories : PHP, Arrays, Variables
Dynamic Calendar in PHP, Javascript and HTML.
Categories : PHP, Java Script, HTML and PHP, Calendar
This functions makes it easy to use session-variables known from ASP. With one Cookie the array "session" will save and restore from a db-record. In this version MySQL is used but it's should very easy to change
Categories : PHP, Arrays, Cookies, MySQL, Databases
The toll booth
Categories : PHP, Java Script, Filesystem