我有以下代码:-
if( $featured_query->have_posts() ): $property_increment = 0;
while( $featured_query->have_posts() ) : $featured_query->the_post();
$town = get_field('house_town');
$a = array($town);
$b = array_unique($a);
sort($b);
var_dump($b);
$property_increment++; endwhile; ?>
<?php endif; wp_reset_query();
var_dump(b)
显示:-
array(1) { [0]=> string(10) "Nottingham" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(11) "Mountsorrel" } array(1) { [0]=> string(12) "Loughborough" }array(1) { [0]=> string(12) "Loughborough" }
var_dump($town)
显示:-
弦(10) "诺丁汉" 弦(9) "莱斯特"弦(9) "莱斯特"弦(11) "芒索雷尔"弦(12) "拉夫堡"弦(12) "拉夫堡"
var_dump($a)
显示:-
array(1) { [0]=> string(10) "Nottingham" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(11) "Mountsorrel" } array(1) { [0]=> string(12) "Loughborough" }array(1) { [0]=> string(12) "Loughborough" }
我想做的是获取$town
的独特值,并将它们输出到一个选择选项中:-
<select>
<option value="Leicester">Leicester</option>';
<option value="Loughborough">Loughborough</option>';
<option value="Mountsorrel">Mountsorrel</option>';
</select>';
在上述alpha中,任何帮助将不胜感激。
#collect all get_field('house_town') in while
$collect[] = get_field('house_town');
#then do the work
$html = implode('',
array_map(
function($a){
return "<option value='{$a}'>{$a}</option>";
},
array_unique($collect)
)
);
在对数组进行排序并使其唯一之前,需要与数组一起取消嵌套array_column
。因此,在初始化$a后,继续如下:
$b = array_unique(array_column($a, 0));
sort($b);
然后制作 HTML:
$html = "";
foreach($b as $town) {
$html .= "<option value='$town'>$town</option>";
}
echo "<select>$html</select>";
如果您没有 array_column
,则可以使用此替换:
function array_column($arr, $column) {
$res = array();
foreach ($arr as $el) {
$res[] = $el[$column];
}
return $res;
}
以下是Chris G的评论和trincot用于生成HTML代码的代码片段的摘要。
注意:出于测试目的,我在此处手动创建了$town数组。将其替换为您的语句 $town = get_field('house_town');
<?php
$town = array(
"Nottingham",
"Leicester",
"Leicester",
"Mountsorrel",
"Loughborough",
"Loughborough"
);
// $town = get_field('house_town');
$html = "";
$town = array_unique($town);
sort($town);
foreach($town as $xtown) {
$html .= "<option value='$xtown'>$xtown</option>";
}
echo "<select>$html</select>";
?>
while/
foreach 循环中的基本/常规唯一用法
//指
$a = array($town); // $a in while/ foreach loop
if(current($a) != next($a)) {
// do your query here // get required unique here
}
注:关怀与分享