我正在尝试迭代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>
答案 0 :(得分:0)
您需要使用foreach
循环遍历JSON,并转义PHP标记,以便输出HTML。
示例:
$str = file_get_contents(base_url(). 'assets/data.json');
$json = json_decode($str, true); // decode the JSON into an associative array
// I assume this is the container, so output that:
echo '<div class="carousel-inner" role="listbox">';
// Now loop through your array, and reference each value you need:
foreach ($json as $value):
?>
<div class="item active">
<div class="testimonialbox">
<img src="<?php echo $value['pic']; ?>" alt="testimonial" />
<p><?php echo $value['desc']; ?></p>
<div class="testimonial-author-box">
<i class="fa fa-quote-right" aria-hidden="true"></i>
<h3><?php echo $value['name']; ?></h3>
<span><?php echo $value['degree']; ?></span>
</div>
</div>
</div>
<?php
endforeach;
// Close the container
echo '</div>';