数组键中每个首字母的唯一ID?

时间:2013-05-03 11:59:45

标签: php

我有一个如下所示的数组:

$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>

知道如何完成它吗?

3 个答案:

答案 0 :(得分: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; ?> ...

答案 1 :(得分: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>

答案 2 :(得分: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>