0

please help me to convert php multi dimension array to JavaScript multi dimension array

Array ( [nonveg] => Array ( [0] => mutton [1] => Chicken ) [veg] => Array ( [2] => sambar [3] => rasam ) )

this is my array value i pass it to JavaScript function i want it to retrieve their in multi dimension array is any body help me how to do that

Edited by Ezzaral: Fixed this mess of a post.

3
Contributors
3
Replies
6
Views
7 Years
Discussion Span
Last Post by wilch
0

Try the code below. You will have to decide what you will do with the js multi dimensional array in the javascript code where there is alert('...').

<?php

	//create your multi lists here
	$list1  	= array("php", "asp.net", "javascript");
	$list2		= array("excellent", "good", "brilliant++");
	$list3		= array("that", "was", "easy !");

	//pass your multi lists to this key variable, then browse this file
	$multiList 	= array($list1, $list2, $list3);

	//don't edit if not sure below this point
	$jsMultiList 	= "";
	$jsArray  	= array();
	$i = 0;
	foreach($multiList as $array){
		$commaString = "";
		foreach($array as $item => $value){
			$commaString .= '"'.$value.'",' ; 	//building js string with comma separators e.g: "php","asp",
		}
		$commaString = rtrim($commaString, ",");	// removing the trailing comma
		$jsArray[$i] = "[$commaString]" ; // pass the comma separated string to an array
		$i++;
	}

	$i 	= 0;
	$count 	= count($jsArray);
	foreach($jsArray as $item => $string){
		$arrayItem 	= $jsArray[$i];
		$jsMultiList 	.= "multiList[$i] = $arrayItem; \n"; //initialising the js array, item by item
		$i++;
	}

	//outputting the javascript array
	echo "<script language='javascript'>
		var multiList = Array($count);
		$jsMultiList
		for(var i=0; i<multiList.length; i++)
		  for(var j=0; j<multiList[i].length ; j++) 
		    alert(multiList[i][j]);
     	      </script>";
	
?>

Edited by wilch: n/a

0

Or you could just do

<script type="text/javascript">
var somejsarray = <?php echo json_encode($somephparray) ?>;
</script>
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.