PHP - 在while循环

时间:2016-01-26 19:52:44

标签: php while-loop

我有以下代码: -

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] =&gt; string(10)&#34;诺丁汉&#34; } array(1){[0] =&gt; string(9)&#34;莱斯特&#34; } array(1){[0] =&gt; string(9)&#34;莱斯特&#34; } array(1){[0] =&gt; string(11)&#34; Mountsorrel&#34; } array(1){[0] =&gt; string(12)&#34; Loughborough&#34; } array(1){[0] =&gt; string(12)&#34; Loughborough&#34; }

var_dump($town)显示: -

  

string(10)&#34; Nottingham&#34; string(9)&#34;莱斯特&#34; string(9)&#34;莱斯特&#34; string(11)&#34; Mountsorrel&#34; string(12)&#34; Loughborough&#34; string(12)&#34; Loughborough&#34;

var_dump($a)显示: -

  

array(1){[0] =&gt; string(10)&#34;诺丁汉&#34; } array(1){[0] =&gt; string(9)&#34;莱斯特&#34; } array(1){[0] =&gt; string(9)&#34;莱斯特&#34; } array(1){[0] =&gt; string(11)&#34; Mountsorrel&#34; } array(1){[0] =&gt; string(12)&#34; Loughborough&#34; } array(1){[0] =&gt; string(12)&#34; Loughborough&#34; }

我想要做的是获取$town的唯一值,并将它们输出到选择选项中: -

 <select>
     <option value="Leicester">Leicester</option>';
     <option value="Loughborough">Loughborough</option>';
     <option value="Mountsorrel">Mountsorrel</option>';
 </select>';

如上所述,我们非常感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

在对数组进行排序并使其唯一之前,您的数组需要与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;
}

答案 1 :(得分:0)

 #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)
             )
         );

答案 2 :(得分:0)

以下是 Chris G的评论 trincot的代码段的摘要,用于生成HTML代码。

注意:出于测试目的,我在这里手动创建了$ town数组。将其替换为您的声明 $ town = get_field(&#39; house_town&#39;);

<?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>";
?>