我有一个数组$myArr['words'],它包含以下格式的数据:
Array (
[above-the-fold] => Array
(
[term] => Above the fold
[desc] => The region of a Web ...
)
[active-voice] => Array
(
[term] => Active voice
[desc] => Makes subjects do ...
)
[backlinks] => Array
(
[term] => Backlinks
[desc] => Used on content ....
)
)我输出的内容如下:
foreach($myArr['words'] as $k => $v) {
echo '
<a href="#'.$k.'">
'.$v['term'].'
</a>';
}如何添加约束以输出仅以特定字符开头的值$k。例如:
$ltr = 'a';发布于 2019-07-24 19:32:03
$test = ['abc'=>'1', 'def'=>'2', 'deh'=>'3'];
foreach($test as $k => $v){
if($k[0] == 'd') {
echo $v . "\r\n";
}
}发布于 2019-07-24 19:56:42
您还可以使用更灵活的方法:通过正则表达式进行匹配。
<?php
$myArr = [
'zzzz' => [
'term' => 'zuzuzu',
'desc' => 'zazaza ...'
],
'above-the-fold' => [
'term' => 'Above the fold',
'desc' => 'The region of a Web ...'
],
'active-voice' => [
'term' => 'Active voice',
'desc' => 'Makes subjects do ...'
],
'backlinks' => [
'term' => 'Backlinks',
'desc' => 'Used on content ....'
]
];
$reg = "/^a/"; // Key starts with "a"
foreach (preg_grep($reg, array_keys($myArr)) as $k => $v)
echo "<a href=\"#$v\" title=\"{$myArr[$v]['desc']}\">{$myArr[$v]['term']}</a>\n";回声:
<a href="#above-the-fold" title="The region of a Web ...">Above the fold</a>
<a href="#active-voice" title="Makes subjects do ...">Active voice</a>发布于 2019-07-24 19:37:19
您可以检查0位置的键:
if(strpos($k, 'a') === 0) {
//echo
}
//or
if($k[0] === 'a') {
//echo
}或者在foreach上过滤数组和$result
$result = array_filter($myArr['words'],
function($v) { return $v[0] === 'a'; },
ARRAY_FILTER_USE_KEY);https://stackoverflow.com/questions/57189962
复制相似问题