简体   繁体   中英

extracting values from associative array in php

I have an array in the following format.

$data = array(
             1=>array('img'=>'1.png','title'=>'title1','desc'=>'desc1'),
             2=>array('img'=>'2.png','title'=>'title2','desc'=>'desc2'),
             1=>array('img'=>'3.png','title'=>'title3','desc'=>'desc3'),
             );

Here is the final output I need,

<img src="1.png">
<h1>title1</h1>
<p>desc1</p>

<img src="2.png">
<h1>title2</h1>
<p>desc2</p>
 .........

How can i create it? Thanks for the help.

Use a foreach loop, like so:

foreach( $data as $item) {
    echo '<img src="' . $item['img'] . '">';
    echo '<h1>' . $item['title'] . '</h1>';
    echo '<p>' . $item['desc'] . '</p>';
    echo "\n";
}

Simply use your array like

  foreach($data as $item){ 
    echo $item['title'];
    .....
  }

This will give you the logic. Now you can apply the img and tags properly

<?php 
        foreach($data as $item) {
        ?>

        <img src="<?=$item['img']?>">
        <h1><?=$item['title']?></h1>
        <p><?=$item['desc']?></p>
        <br />

        <?php } ?>

Another option here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM