我看到两种方法:
1)在当前状态下传递数组:
<?php
$array = [
[ 'name' => 'x' , 'value' => 1 ],
[ 'name' => 'y' , 'value' => 2 ],
[ 'name' => 'z' , 'value' => 3 ]
];
?>
<script type="text/javascript">
var php_json = <?php echo json_encode($array); ?>;
for(var i = 0; i < php_json.length; i++){
console.log(php_json[i]);
}
</script>
2)转换为键值对并传递:
<?php
$array = [
[ 'name' => 'x' , 'value' => 1 ],
[ 'name' => 'y' , 'value' => 2 ],
[ 'name' => 'z' , 'value' => 3 ]
];
$buffer = [];
foreach($array as &$nested){
$buffer[$nested['name']] = $nested['value'];
}
?>
<script type="text/javascript">
var php_json = <?php echo json_encode($buffer); ?>;
for(var key in php_json){
console.log(key, php_json[key]);
// key ^ ^ value
}
</script>
您可以通过 usingjson_encode()
函数轻松地将任何简单的 php 数据结构传递给 javascript。