为对象数组动态生成<li>列表项html节</li>

时间:2014-12-20 18:30:46

标签: php html

我是PHP的初学者,坦白说,就在几天前开始 我想用php动态创建下面的html部分。

<div class="main">
<ul id="og-grid" class="og-grid">

<li>
    <a href="#" data-largesrc="imgURL of index[1] item" data-title="title of index[1] item"
       data-description="descrition of index[1] item">
        <img src="imgUrl of index[1] item" alt="img01"/>
    </a>
</li>
<li>
    <a href="#" data-largesrc="imgUrl of index[2] item" data-title="title of index[2] item"
       data-description="descrition of index[2] item">
        <img src="imgUrl of index[2] item" alt="img02"/>
    </a>
</li>

// Like this for a size of an array

<li>
     <a href="#" data-largesrc="imgUrl of index[n] item" data-title="title of index[n] item"
           data-description="descrition of index[n] item">
            <img src="imgUrl of index[n] item" alt="img02"/>
     </a>
</li>

</ul>
</div> 

这是我试过的,但代码并没有完成,因为我被困在这个

echo '<div class="main">';
echo '<ul id="og-grid" class="og-grid">';

for ($row = 0; $row < sizeof($vodAssetArray); $row++)
{
    echo '<li><a href="#"><img src =""></img></a></li>';
}

请你帮我解决一下。

2 个答案:

答案 0 :(得分:3)

尝试查看PHP foreach

基本上你需要和类数组(或数组),例如,基本类可能是这样的:

class Item {
    public $title;
    public $description;
    public $url;
}

然后创建新对象并将它们放在数组中:

$picture = new Item();
$picture->url = "http://linktomypicture.com";
$picture->title = "Sample Title for picture";
$picture->description = "Sample description for my picture";
$array_of_pictures[] = $picture;

迭代它们:

foreach ($array_of_pictures as $picture) {
    echo "<li>";
    echo "<a href='{$picture->url}' data-largesrc='{$picture->url}'";
    echo "data-title='{$picture->title}'";
    echo "data-description='{$picture->descrition}'>";
    echo "<img src='{$picture->url}' alt='{$picture->title}'/>";
    echo "</a>";
    echo "</li>";
}

答案 1 :(得分:0)

打开php范围并像这样关闭它们。 li项将在for()范围内生成

<div class="main">
<ul id="og-grid" class="og-grid">
<?php for($i = 0; $i < $listLebght; $i++)
{
?>

<li>
    <a href="#" data-largesrc="array->imgUrl" data-title="array->title"
       data-description="array->descrition">
        <img src="<?php echo $src; ?>" alt="img02"/>
    </a>
</li>
<?php
}
?>
</ul>
</div>