PHP array to Javascript Array

Hello,

I hope I am writing this in the correct thread.

I have pasted relevant code below.

		/* convert PHP array ($levels) to Javascript array ($param) */
	for($x = 0; $x < count($levels); $x++)
	{
		$array .= "[" . $levels[$x][0] . ", ". $levels[$x][1] . "]" ;
		if($x+1 < count($levels))
			$array .= ", ";
	}
	$param = "new Array( " . $array . ")";
	/* end convert PHP array to Javascript array */
	
	
	echo '<form name="SubjectForm">';
	echo 'Subject <br><select name = "subject" onChange="addOptions('. $param . ') ">';
            echo '</form>;'

The output of the multi-dimensional array conversion becomes something like this:
new Array( [Math, Algebra I], [Math, Algebra II], [Math, Arithmetic], [Math, Calculus], [Math, Pre-Algebra], [Math , Pre-Calculus], [Math, Statistics], [Math, Trigonometry], [Science, Biology], [Science, Chemistry], [Science, Earth Science], [Science, Physics])

I created a literal declaration of an array and I want to pass it to the addOptions function which is called with an onChange event handler. But when I pass this $param variable, the addOptions function doesn’t work.

However if I manually create a parameter that is an array similar to:
echo ‘Subject <br><select name = “subject” onChange="addOptions( new Array( [1, 2], [3, 4]) ">’;

Then the addOptions function works. So I guess my question is, what am I doing wrong with my conversion of the PHP array to the JS array that is making the addOptions not work?

Thank you very much ahead of time for any help. Take care.

I’m not a JavaScript expert so I’m not sure if your problem is with JavaScript syntax or the data values you’re using. But below is a PHP junction that generates a JavaScript array constant from a PHP array structure. The following code shows an example PHP array and how the JavaScript code using the array constant can be created. Note that the makeJavaScriptArray() function is in production use but the other code is just sample code and could be buggy.


$phpArray = array();
$phpArray['string'] = 'text string';
$phpArray['number'] = 1234;
$phpArray['boolean'] = FALSE;
$subArray = array();
$subArray[] = 'text string';
$subArray[] = 1234;
$subArray[] = TRUE;
$phpArray['array'] = $subArray;
$javaScriptCode = 'javaScriptVariable = ' . htmlentities( makeJavaScriptArray( $phpArray ) );

//
//  makeJavaScriptArray - Returns a JavaScript array constant created from the provided PHP nested array.
//                        this function is typically called to create a response to an Ajax request.
//
//  Note: While this function will protect the JavaScript code from special characters, the calling code
//        still needs to encode any HTML entities before sending the result to the browser.
//

function makeJavaScriptArray( $phpArray )
{
	$arrayConstant = '{';
	$delimiter = '';
	
	foreach ($phpArray as $fieldName => $fieldValue)
	{
		if (is_bool( $fieldValue ))									// Boolean data type
			if ($fieldValue) $fieldConstant = 'true';
			else $fieldConstant = 'false';
		
		elseif (is_numeric( $fieldValue ))							// Numeric data type
			$fieldConstant = $fieldValue;
		
		elseif (is_string( $fieldValue ))							// String data type
			$fieldConstant = "'" . addSlashes( $fieldValue ) . "'";
			
		elseif (is_array( $fieldValue ))							// Array data type
			$fieldConstant = makeJavaScriptArray( $fieldValue );
			
		else														// Unknown data type
			$fieldConstant = '';
		
		if ($fieldConstant > '')
		{
			$arrayConstant .= $delimiter . " '$fieldName': $fieldConstant";
			$delimiter = ',';
		}
	}

Hope this helps…
mikem

If i have understood what you are trying to do, the following example should help you there:


$arr = array(1,2,3,4,5,6,7);
$script = '<script>var newArr = new Array(' . implode(',', $arr) . ');</script>';
echo $script;


<script>
function doOnchange(arr){
	alert(arr.length);
}
</script>
<form name="frm">
	<select name="sel1" onchange="doOnchange(newArr);">
		<option>1</option>
		<option>2</option>
		<option>3</option>
	</select>
</form>

[FPHP]json_encode[/FPHP]. If you don’t have the extension enabled, there is a workaround in the comments of that page.

Use json_encode.

If you have a PHP array with name $arrSample, then convert it to JSON string by using code below:

$jsonString = json_encode($arrSample);
then echo it.

On the client side, use eval or JSON.parse(to use this function, you need to download JSON2.js from http://www.json.org/).

evaluate the JSON string in JavaScript using

jsonObj = eval( ‘(’ + <<JSON String>> + ‘)’);

Now jsonObj is the JavaScript version of PHP array. :slight_smile:

You don’t need to use eval on the client side. JSON is a valid subset of Javascript, so you can simply do:


var json = <?php echo json_encode($foo); ?>;

Yes, you need to eval it when it is coming in response to an Ajax request.