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