我有一个关联的 PHP 数组,我需要在 Javascript 中访问它来检查manufacturer. 我目前正在页面上内联输出,然后在单独的 JS 文件中读取。<?php$carsData = array();foreach ($cars as $car) { $carsData[] = ['id' => $car->id, 'title' => $car->title, 'manufacturer' => $car->manufacturer];}$carsDataString = json_encode($carsData);?><script>carsData = <?php echo $carsDataString . ';';?></script>到目前为止,这有效 - 源代码完全按照我的预期显示:carsData = [{"id":2,"title":"Astra","manufacturer":"2"},{"id":3,"title":"Tepee","manufacturer":"3"},{"id":4,"title":"C4 Grand","manufacturer":"4"},{"id":5,"title":"Civic","manufacturer":"5"},{"id":6,"title":"Jazz","manufacturer":"5"}];到目前为止,在我尝试用 JS 阅读本文的过程中,我有以下内容: $.each(carsData, function(key, value) { console.log(key['manufacturer']); });在我的控制台中,这是输出undefined, undefined, undefined, undefined. 如果我carsData在控制台中执行,我会看到与我期望的完全一样的对象。那么我做错了什么?我需要能够接受这个并执行以下操作: $.each(carsData, function(key, value) { if (key['manufacturer'] = 5 { $('#manufacturer' + key['manufacturer'].show(); } });请注意,我已将其简化为值“5”,因为该值实际上来自另一个脚本,并且按照我的预期在那里打印 5。
- 3 回答
- 0 关注
- 129 浏览
添加回答
举报
0/150
提交
取消