数组键中每个第一个字母的唯一ID?
问题描述:
我有一个数组,看起来像这样:数组键中每个第一个字母的唯一ID?
$array = array(
"aceton" => "description here",
"acetonurie" => "description here",
"adipositas" => "description here",
"bolus" => "description here",
"cataract" => "description here",
"cortisol" => "description here",
);
接下来我建立使用数组数据definitionlist:
<dl>
<?php foreach ($array as $key => $value): ?>
<dt><?php echo $key; ?><dd><?php echo $value; ?>
<?php endforeach; ?>
</dl>
这工作正常offcourse但我需要更多的东西。 我需要一种方法来生成每个独特的首字母编号,所以结果就变成了:
<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>
不知道如何把它做?
答
试试这个,
<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>
+0
感谢您的时间人们,我现在工作得很好。 – Fortron 2013-05-03 12:20:20
答
只是跟踪使用另一个数组第一个字母:
$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; ?> ...
答
就跟踪当前的字母。如果它改变,显示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>
你的HTML是无效的。你需要关闭你的'dt'和'dd'标签。 – danronmoon 2013-05-03 12:03:52
@danronmoon你当然认为已经指定了一个xhtml文档类型,因为在任何[html规范](http://www.w3.org)中省略'dt'和'dd'元素的结束标记是完全合法的/TR/2011/WD-html5-20110525/syntax.html#syntax-tag-omission)。 – Emissary 2013-05-03 12:16:18