目前我正在重建我的网站,我正在使用Wordpress自定义程序将一些主页特定数据设置到相应的部分。
我已经在Wordpress后端安装了数据,但是我在前端拆分时遇到了麻烦。
我能够在数组中获取所有Wordpress自定义程序值,并根据部分字符串的第一部分对其进行过滤。
例如,我使用以下php代码过滤我的时间轴项目:
<?php
$home_options = get_theme_mods();
foreach ($home_options as $key => $value) {
if (strpos($key, "timeline_item") === 0) {
echo '<strong>'.$key.'</strong> = '.$value.'<br />';
}
}
?>
这给了我以下数据:
timeline_item_1_enable = 1
timeline_item_1_title = Test item 1
timeline_item_1_duration = 2010 - 2014
timeline_item_1_text = Test item 1 text
timeline_item_2_enable = 1
timeline_item_2_title = Test item 2
timeline_item_2_duration = 2014 - 2014
timeline_item_2_text = Test item 2 text
timeline_item_3_enable = 1
timeline_item_3_title = Test item 3
timeline_item_3_duration = 2010 - 2014
timeline_item_3_text = Test item 3 text
timeline_item_4_enable = 1
timeline_item_4_title = Test item 1
timeline_item_4_duration = 2010 - 2014
timeline_item_4_text = Test item 4 text
这工作正常,我得到了我需要的所有时间线数据。但是,根据该数据,我想提取所有以timeline_item_1_
开头的项目,并将它们捆绑到<div>
,同样地timeline_item_2_
等等
所以问题是,我如何进一步拆分结果数组,并根据字符串的第一部分捆绑所有彼此相关的项目,最终结果如下,
<div>
timeline_item_1_enable = 1
timeline_item_1_title = Test item 1
timeline_item_1_duration = 2010 - 2014
timeline_item_1_text = Test item 1 text
</div>
<div>
timeline_item_2_enable = 1
timeline_item_2_title = Test item 2
timeline_item_2_duration = 2014 - 2014
timeline_item_2_text = Test item 2 text
</div>
<div>
timeline_item_3_enable = 1
timeline_item_3_title = Test item 3
timeline_item_3_duration = 2010 - 2014
timeline_item_3_text = Test item 3 text
</div>
<div>
timeline_item_4_enable = 1
timeline_item_4_title = Test item 1
timeline_item_4_duration = 2010 - 2014
timeline_item_4_text = Test item 4 text
</div>
答案 0 :(得分:0)
<?php
$home_options = get_theme_mods();
$regex = '/([a-z]*)_([a-z]*)_(\d)_([a-z]*)/';
$parts = [];
foreach ($home_options as $key => $value) {
preg_match_all($regex, $key, $matches, PREG_SET_ORDER, 0);
/* $matches have the matches below
Full match 0-22 `timeline_item_1_enable`
Group 1. 0-8 `timeline`
Group 2. 9-13 `item`
Group 3. 14-15 `1`
Group 4. 16-22 `enable`
*/
$pkey = 'timeline_item_'.$matches[0][3];
if (!isset($parts[$pkey])) $parts[$pkey] = array($key => $val);
else $parts[$pkey][$key] = $val;
}
foreach($parts as $pkey => $props) {
echo '<div>';
foreach($props as $key => $val) {
echo $key . ' = ' . $val . '<br>';
}
echo '</div>';
}
?>
检查正则表达式here。
答案 1 :(得分:0)
您可以使用array_chunk以保留键true分开四个数组,并在内循环中循环每组四个。
Foreach(array_chunk($arr, 4, true) as $val){
Echo "<div>\n";
Foreach($val as $key => $v){
echo '<strong>'.$key.'</strong> = '.$v."<br />\n";
}
Echo "</div>\n";
}