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

Recommended Answers

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", …
Jump to Post

All 3 Replies

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>";
	
?>

Or you could just do

<script type="text/javascript">
var somejsarray = <?php echo json_encode($somephparray) ?>;
</script>

Wow - now that's real efficiency.
I should have known of this months ago.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.