【发布时间】:2019-01-08 23:20:23
【问题描述】:
我正在尝试迭代 JSON 数组并在 DOM 中显示元素? 我的 JSON 架构
[
{
"pic": "<?php echo base_url();?>assets/images/testi_pic1.jpg",
"desc": "My experience with Vestedu has been great. I was able to save money on my student loan, they have competitive rates, excellent customer service and easy application process",
"name": "Ram Chandra",
"degree": "MBA",
"desig": "designation"
},
{
"pic": "<?php echo base_url();?>assets/images/testi_pic2.jpg",
"desc": "My experience with Vestedu has been great. I was able to save money on my student loan, they have competitive rates, excellent customer service and easy application process",
"name": "Ram Chandra",
"degree": "MBA",
"desig": null
}
]
我的 PHP 代码
<?php
$str = file_get_contents(base_url(). 'assets/data.json');
$json = json_decode($str, true); // decode the JSON into an associative array
$count = count($json);
for ($i=0; $i < $count; $i++) {
echo '<pre>' . print_r($json[$i], true) . '</pre>';
}
?>
现在我可以从数组中提取对象,我该如何遍历这个 HTML?
<div class="carousel-inner" role="listbox">
<div class="item active">
<div class="testimonialbox">
<img src="<?php echo base_url();?>assets/images/testi_pic1.jpg" alt="testimonial" />
<p>"My experience with Vestedu has been great. I was able to save money on my student loan, they have competitive rates, excellent customer service and easy application process"</p>
<div class="testimonial-author-box">
<i class="fa fa-quote-right" aria-hidden="true"></i>
<h3>Ram Chandra</h3>
<span>MBA</span>
</div>
</div>
</div>
【问题讨论】:
-
改用foreach循环。
-
这个问题是如何再次从 JSON 跳到 HTML 的?
-
@mario 我想在 PHP 内部的 HTML 中呈现 JSON 对象
-
所以
echo "<h3>{$json[$i]["name"]}</h3>";基本上? (顺便说一句,字符串中带有<?php echo base_url的蠕虫罐头是另一个问题。)