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

Dani AI

Generated

Quick summary and the important caveat from the sample thread: ’s manual string-building works but is verbose; ’s json_encode idea is the cleanest. One key gotcha not shown in those replies is PHP’s encoding rules — a PHP array with non-sequential numeric keys (for example the OP’s veg items indexed as 2 and 3) will be encoded as a JSON object, not a JSON array. That distinction changes how the data is consumed in JavaScript.

A safe, practical flow for Joomla pages is:

  • Reindex any numeric sub-arrays that must become JS arrays.
  • json_encode the PHP structure with escaping flags to reduce XSS risk.
  • Add the resulting script with Joomla’s document API (avoids ad-hoc echoing into the template).

Example (PHP):

foreach ($phpArray as $k => $v) {
    if (is_array($v)) {
        $keys = array_keys($v);
        if ($keys !== range(0, count($v) - 1)) {
            $phpArray[$k] = array_values($v); // reindex numeric sub-array
        }
    }
}

$doc = JFactory::getDocument();
$script = 'var menuData = ' . json_encode($phpArray, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT) . ';';
$doc->addScriptDeclaration($script);

Notes and troubleshooting:

  • Reindexing with array_values forces a JSON array ([...]) instead of an object ({...}).
  • Use the JSONHEX* flags (shown above) when embedding JSON into inline scripts to help prevent accidental HTML/script injection.
  • If json_encode fails or returns null, check for invalid UTF-8 in strings (convert to UTF-8 first) and inspect json_last_error() / json_last_error_msg().
  • For sites with strict CSP or very large payloads, prefer exposing JSON via a dedicated AJAX endpoint or data attribute instead of inline scripts.
  • Associative PHP arrays become JS objects — that is often fine and sometimes preferable.

This ties ’s and ’s ideas together while ensuring the encoded data has the expected JS structure.

Recommended Answers

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 developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.