簡體   English   中英

如何在PHP中迭代JSON數組並顯示元素?

[英]How do I iterate JSON Array and display elements in PHP?

我正在嘗試迭代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,並轉義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>';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM