0

我在 php 中有一个数组,在执行 print_r($breadcrumb) 时看起来像这样

Array (
    [url] => /category/
    [text] => Category
)
Array (
    [url] => /category/subcategory/
    [text] => Subcategory
)
Array (
    [url] => /category/subcategory/subsubcategory/
    [text] => Subsubcategory
)

我希望这个面包屑显示为

Category > Subcategory > Subsubcategory

根据Google 文档,HTML 应如下所示:

<div xmlns:v="http://rdf.data-vocabulary.org/#"> 
  <span typeof="v:Breadcrumb">
    <a href="/category/" rel="v:url" property="v:title">
      Category
    </a> ›
    <span rel="v:child">
      <span typeof="v:Breadcrumb">
        <a href="/category/subcategory/" rel="v:url" property="v:title">
          Subcategory
        </a> ›
        <span rel="v:child">         
          <span typeof="v:Breadcrumb">
            <a href="/category/subcategory/subsubcategory/" rel="v:url" property="v:title">
              Subsubcategory
            </a> ›          
          </span>
        </span>
      </span>
    </span>
  </span>
</div>

如何从 PHP 数组转到 HTML?

我看过其他答案,但它们在我的场景中不起作用

4

1 回答 1

1

以下是我将如何解决这个问题:

PHP:

<?php
    $breadcrumb = array(
        array(
            'url' => '/category/',
            'text' => 'Category'
        ),
        array(
            'url' => '/category/subcategory/',
            'text' => 'Subcategory'
        ),
        array(
            'url' => '/category/subcategory/subcategory',
            'text' => 'Subsubcategory'
        )
    );
    $children = count($breadcrumb) - 1;
?>

显示标记:

<div xmlns:v="http://rdf.data-vocabulary.org/#">
    <span typeof="v:Breadcrumb">
        <?php for ($i = 0; $i < count($breadcrumb); $i++) : ?>
        <?php if ($i == 0) : ?>
        <a href="<?php echo $breadcrumb[0]['url']; ?>" rel="v:url" property="v:title"><?php echo $breadcrumb[0]['text']; ?></a> › 
        <?php else : ?>
        <span rel="v:child">
            <span typeof="v:Breadcrumb">
                <a href="<?php echo $breadcrumb[$i]['url']; ?>" rel="v:url" property="v:title"><?php echo $breadcrumb[$i]['text']; ?></a> ›
        <?php endif; ?> 
        <?php endfor; ?>
        <?php echo str_repeat("</span>\r\n</span>\r\n", $children); ?>
    </span>
</div>

如有必要,这种方法还将允许更深的子类别。

希望能帮助到你

更新显示代码:

<div xmlns:v="http://rdf.data-vocabulary.org/#">
    <span typeof="v:Breadcrumb">
        <?php for ($i = 0; $i < count($breadcrumb); $i++) : ?>
        <?php if ($i == 0) : ?>
        <a href="<?php echo $breadcrumb[0]['url']; ?>" rel="v:url" property="v:title"><?php echo $breadcrumb[0]['text']; ?></a> › 
        <?php else : ?>
        <span rel="v:child">
            <span typeof="v:Breadcrumb">
                <a href="<?php echo $breadcrumb[$i]['url']; ?>" rel="v:url" property="v:title"><?php echo $breadcrumb[$i]['text']; ?></a><?php if ($i < $children):?> › <?php endif; ?>
        <?php endif; ?> 
        <?php endfor; ?>
        <?php echo str_repeat("</span>\r\n</span>\r\n", $children); ?>
    </span>
</div>

上面的代码从末尾修剪了最后一个 > 符号:)

于 2013-03-08T10:48:13.263 回答