PHP echo数组帮助

时间:2010-11-07 21:52:49

标签: php arrays multidimensional-array

我有一个这样的数组:

Array
(
    [1197624] => Array
        (
            [0] => Array
                (
                    [datetime] => 2010-11-06 21:32:56
                    [movieID] => 1197624
                    [personID] => 0
                    [filename] => 1197624.jpg
                    [more indexes]...
                )
            [1] => Array
                (
                    [datetime] => 2010-11-06 21:25:53
                    [movieID] => 1197624
                    [personID] => 0
                    [filename] => 1197624.jpg
                    [more indexes]...
                )
        )
    [0987657] => Array
        (
            [0] => Array
                (
                    [datetime] => 2010-11-06 21:38:07
                    [movieID] => 0
                    [personID] => 0987657
                    [filename] => 0987657.jpg
                    [more indexes]...
                )
            [1] => Array
                (
                    [datetime] => 2010-11-06 21:55:09
                    [movieID] => 0
                    [personID] => 0987657
                    [filename] => 0987657.jpg
                    [more indexes]...
                )
        )
    [5467023] => Array
        (
            [0] => Array
                (
                    [datetime] => 2010-11-06 21:59:33
                    [movieID] => 5467023
                    [personID] => 0
                    [filename] => 5467023.jpg
                    [more indexes]...
                )


        )
)

我想像这样回应它(注意键是如何分组的):

<div>
  <img src="../1197624.jpg" />
  <p>1197624</p>
  <ul>
    <li>2010-11-06 21:32:56</li>
    <li>2010-11-06 21:25:53</li>
  </ul>
</div>

<div>
  <img src="../0987657.jpg" />
  <p>0987657</p>
  <ul>
    <li>010-11-06 21:38:07</li>
    <li>2010-11-06 21:55:09</li>
  </ul>
</div>

<div>
  <img src="../5467023.jpg" />
  <p>5467023</p>
  <ul>
    <li>02010-11-06 21:59:33</li>
  </ul>
</div>

怎么做?

2 个答案:

答案 0 :(得分:3)

foreach ($array as $k => $vals) {
    echo "<div>\n";
    echo "  <img src=\"../" . $vals[0]["filename"] . "\" />\n";
    echo "  <p>" . $k . "</p>\n";
    echo "  <ul>\n";
    foreach ($vals as $v) {
        echo "    <li>" . $v["datetime"] . "</li>\n";
    }
    echo "  </ul>\n";
    echo "</div>\n";
}

这里有一些假设:

  • 顶级数组中的每个元素都至少有一个元素作为其值(以便可以从第一个元素获取img标记的文件名。)
  • 对于顶级数组的每个元素,条目值中的文件名是相同的(如果不是,第一个可能不是正确的选择)。

答案 1 :(得分:0)

粗略的结构将如下所示:

foreach ($array as $key => $element)
 {
       ... echo opening div....

       echo $key; // 1197624
       ...
       echo $element[0]["datetime"]; // 2010-11-06 21:32:56
       echo $element[1]["datetime"]; // 2010-11-06 21:25:53
       ...

       ... echo closing div....


 }