WP輸出數組:PHP合併數組(S)和刪除雙重價值
$therapie = get_post_meta($post->ID, 'Therapieen', false);
print_r($therapie);
//the output of print_r
Array ([0] => Massagetherapie)
Array ([0] => Hot stone)
Array ([0] => Massagetherapie)
我怎麼會合並這些陣列之一,並刪除所有的確切雙的名字呢?
在像這樣得到的:
theArray
(
[0] => Massagetherapie
[1] => Hot stone
)
[解決]問題是,如果你這樣做在一個while循環,它不會在這裏工作我的解決方案,TY所有回覆的和好的代碼:其運行循環並推動數組中的每個結果。
<?php query_posts('post_type=therapeut');
$therapeAr = array(); ?>
<?php while (have_posts()) : the_post(); ?>
<?php $therapie = get_post_meta($post->ID, 'Therapieen', true);
if (strpos($therapie,',') !== false) { //check for , if so make array
$arr = explode(',', $therapie);
array_push($therapeAr, $arr);
} else {
array_push($therapeAr, $therapie);
} ?>
<?php endwhile; ?>
<?php
function array_values_recursive($ary) { //2 to 1 dim array
$lst = array();
foreach(array_keys($ary) as $k) {
$v = $ary[$k];
if (is_scalar($v)) {
$lst[] = $v;
} elseif (is_array($v)) {
$lst = array_merge($lst,array_values_recursive($v));
}}
return $lst;
}
function trim_value(&$value) //trims whitespace begin&end array
{
$value = trim($value);
}
$therapeAr = array_values_recursive($therapeAr);
array_walk($therapeAr, 'trim_value');
$therapeAr = array_unique($therapeAr);
foreach($therapeAr as $thera) {
echo '<li><input type="checkbox" value="'.$thera.'">'.$thera.'</input></li>';
} ?>
Gumbo給我的建議:'array_unique()'和'array_keys(array_flip())'都完成同樣的事情,除了他們有時間複雜性'O(nlogn )'和'O(n)'。 – erisco 2011-05-30 20:15:27
@erisco很酷,感謝分享! – anomareh 2011-05-30 20:24:04
ty,這段代碼很可能會起作用,但可惜我無法讓它正常工作。我想這與處理3個不同數組的變量$ therapie有關。爲了記錄,我已經嘗試了上面的所有代碼示例。 – Rob 2011-05-30 21:06:12