在PHP中匹配关键字文本的数组子集中循环


Loop in subset of an array matching key text in PHP

我有这个数组(使用PHP):

Array
(
[dummy_value_01] => 10293
[other_dummy_value_01] => Text
[top_story_check] => 1
[top_story_hp] => 1
[top_story] => 248637
[top_story_id] => 100
[top_story_text] => 2010
[menu_trend_01] => 248714
[menu_trend_01_txt] => Text 01
[menu_trend_02] => 248680
[menu_trend_02_txt] => Text 02
[menu_trend_03] => 248680
[menu_trend_03_txt] => Text 03
[menu_trend_04] => 248680
[menu_trend_04_txt] => Text 04
[menu_trend_05] => 248680
)

我想只循环menu_trend_*值并获得如下列表:

<ul>
<li>Text 01: 248714</li>
<li>Text 02: 248680</li>
<li>[...]</li>
</ul>

你能建议最好的方法吗?

您可以使用这个,它将尝试匹配menu_trend_(DIGIT),如果匹配,将回显所需的文本。

echo '<ul>';
foreach ($array as $key => $val) {

    $matches = array();
    if (!preg_match('/^menu_trend_('d+)$/', $key, $matches)) {
        continue;
    }
    echo sprintf('<li>Text %s: %s</li>', $matches[1], $val);
}
echo '</ul>';

我不确定这是最好的方法,但它会工作:

$output = array();
foreach ($array as $k => $a) {
  if (stristr($k, 'menu_trend_') && !empty($arr[$k . '_txt'])) {
    $output[] = $arr[$k . '_txt'] . ': ' . $a;
  }
}
echo "<ul>'n<li>" . implode("</li>'n<li>", $output) . "</li>'n</ul>";

下面是一个工作示例