WP 输出一个数组:
$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 循环中执行此操作,它不会在这里工作
<?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>';
} ?>
最佳答案
下面应该可以解决问题。
$flattened = array_unique(call_user_func_array('array_merge', $therapie));
或更有效的替代方案(感谢 erisco 的评论):
$flattened = array_keys(array_flip(
call_user_func_array('array_merge', $therapie)
));
如果 $therapie
的键是字符串,您可以删除 array_unique
。
或者,如果您想避免call_user_func_array
,您可以研究展平多维数组的各种不同方法。这里有一些(one,two)关于 SO 的好问题,详细说明了这样做的几种不同方法。
我还应该注意,这只有在 $therapie
只是一个二维数组时才有效,除非您不想将其完全展平。如果 $therapie
超过 2 个维度并且您想将其展平为 1 个维度,请查看我上面链接的问题。
相关文档条目:
array_flip
array_keys
array_merge
array_unique
call_user_func_array
关于PHP 合并数组并删除双值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6180090/