I use a webservice to create a PHP array $result, but when passed to javascript and JSON.parse, nothing results. I am a newbie with php and JS arrays, have done much googling, but cannot find the answer. Help welcome!
First the output in a browser, where the PHP array prints out, but the javascript does not output anything:-
1) Results of PHP array print
Array
(
[hotels] => Array
(
[codigo] => LIMHBM
[fecha] => 2016/9/15
[cannoc] => 1
[canhab] => 1
[canpax] => 2
[estado] => OK
)
)
2) Results of JSON parse: none
1) Results of PHP array print
<pre><?php print_r($result); ?></pre>
2) Results of JSON parse:
<span id="demo">none</span>
<script type="text/javascript">
var result = JSON.parse( '<?php echo json_encode($result) ?>' );
document.getElementById("demo").innerHTML = result.hotels[0].codigo + " " + result.hotels[0].estado;
</script>
Actually your code is right till the last line of javascript code which is:-
document.getElementById("demo").innerHTML = result.hotels[0].codigo + " " + result.hotels[0].estado;
Change it to:-
document.getElementById("demo").innerHTML = result.hotels.codigo+ " " + result.hotels.estado;
Example:-
<?php
$result = Array
(
'hotels' => Array
(
'codigo' => 'LIMHBM',
'fecha' => '2016/9/15',
'cannoc' => 1,
'canhab' => 1,
'canpax' => 2,
'estado' => 'OK'
)
);
?>
1) Results of PHP array print
<?php echo "<pre/>";print_r($result); ?>
2) Results of JSON parse:
<span id="demo">none</span>
<script type="text/javascript">
var result = JSON.parse('<?php echo json_encode($result) ?>');
console.log(result); // to just show you te output in console
document.getElementById("demo").innerHTML = result.hotels.codigo+ " " + result.hotels.estado;
</script>
Output:- http://prntscr.com/avm729
For multidimensional array help, check this:-