0

我有一个看起来像这样的数组:

$array = array(
    "aceton" => "description here",
    "acetonurie" => "description here",
    "adipositas" => "description here",
    "bolus" => "description here",
    "cataract" => "description here",
    "cortisol" => "description here",
);

接下来我使用数组数据构建一个定义列表:

<dl>
<?php foreach ($array as $key => $value): ?>
<dt><?php echo $key; ?><dd><?php echo $value; ?>
<?php endforeach; ?>
</dl>

这很好用,但我需要更多的东西。我需要一种方法来为每个唯一的首字母生成一个 id,因此结果变为:

<dl>
<dt id="a">aceton <dd>description here
<dt>acetonurie <dd>description here
<dt>adipositas <dd>description here
<dt id="b">bolus <dd>description here
<dt id="c">cataract <dd>description here
<dt>cortisol <dd>description here
et cetera..
</dl>

知道如何完成吗?

4

3 回答 3

1

只需使用另一个数组跟踪第一个字母:

$letters = array();

?>
<dl>
<?php foreach ($array as $key => $value): ?>
  <?php $id = in_array($key[0], $letters) ? '' : ' id="' . $key[0] . '"'; ?>
  <dt<?php echo $id; ?>><?php echo $key; ?> ...
于 2013-05-03T12:03:48.617 回答
0

只需跟踪当前的信件。如果它发生变化,请显示 id 字段。

<dl>
<?php 
    $currentLetter = null;
    foreach ($array as $key => $value){
?>
    <dt<?php echo ($currentLetter == substr($value, 0, 1)) ? 'id="'.substr($value, 0, 1).'"' : ""?>><?php echo $key; ?><dd><?php echo $value; ?>
<?php 
    $currentLetter = substr($value, 0, 1);
    }
?>
</dl>
于 2013-05-03T12:07:07.140 回答
0

尝试这个,

   <dl>
  <?php 
    $tmp=array();

    foreach ($array as $key => $value): ?>

  <dt <?php if(!in_array($key[0],$tmp))
   { echo "id='".$key[0]."'"; array_push($tmp,$key[0]); } ?> >
  <?php echo $key; ?>
  </dt>

   <dd><?php echo $value; ?></dd>

 <?php endforeach; ?>
  </dl>

我有,

     <dl>
     <dt id="a">aceton</dt><dd>description here</dd>
     <dt>acetonurie</dt><dd>description here</dd>
     <dt>adipositas</dt><dd>description here</dd>
     <dt id="b">bolus</dt><dd>description here</dd>
     <dt id="c">cataract</dt><dd>description here</dd>
     <dt>cortisol</dt><dd>description here</dd>
    </dl>
于 2013-05-03T12:13:09.337 回答