...

View Full Version : Construct Javascript array of objects



name _F1
01-15-2008, 07:16 AM
I want to construct a Javascript array of objects using a set of data from MySQL. The format should be as follows:

var arr = [{ //Begin array literal, begin object literal
id: 1,
title: "Test",
date: new Date(2008,1,1,1,0,0)
}, //Close object literal, move to next array element
{
id: 2,
title: "Test2",
date: new Date(2008,1,1,1,0,0)
}] //Close array literal, note no comma on the last array element

The array is constructed through a while loop of the MySQL result. My problem is that I don't want to have a comma at the end before I close the array. This is the code I have at the moment:



//MySQL data has already been retrieved
echo 'var arr = [';
while($row = mysql_fetch_array($result)) {
echo '{ id: '.$row['id'];
echo ', title: "'.$row['title'].'"';
echo ', date: new Date('.$row['date'].') },'; //Note comma, results in a comma at the end of the array
}
echo '];';
}


How can I stop the final comma being added?

shyam
01-15-2008, 07:21 AM
//MySQL data has already been retrieved
$first = true;
echo 'var arr = [';
while($row = mysql_fetch_array($result)) {
if ( !$first ) {
echo ',';
} else {
$first = false;
}
echo '{ id: '.$row['id'];
echo ', title: "'.$row['title'].'"';
echo ', date: new Date('.$row['date'].') }'; //look ma, no comma
}
echo '];';
}

hammer65
01-15-2008, 03:59 PM
$first = true;
echo ;
$objs = array();
while($row = mysql_fetch_array($result)) {
$objs[] =<<<JSOBJ
{id:{$row['id']},title:"{$row['title']}",date:new Date({$row['date']})}
JSOBJ;
}
echo 'var arr = ['.implode(',',$objs).'];';
}
In PHP 5.x (I think it can also be installed in 4.x) there is a JSON extension that will convert PHP data structures to JSON and also do the reverse. If that extension is present, it would be much quicker to use it.

GJay
01-15-2008, 07:16 PM
yeah, use json_encode or you're going to get caught out with any special characters that might be in your data.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum