PHP合并数组并删除双值


PHP merge array(s) and delete double values

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
)

[解决了]问题是,如果你在一段时间内这样做,它在这里就不起作用了,我的解决方案,对所有回复和好代码来说都是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>';
} ?>                 

以下内容应该可以完成任务。

$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,你可以研究各种不同的方法来压平多维数组。这里有几个(一两个)好问题已经在SO详细介绍了几种不同的方法

我还应该注意,只有当$therapie只是一个二维数组时,这才会起作用,除非您不想完全压平它。如果$therapie超过2个维度,并且您想将其展平为1个维度,请查看我上面链接的问题。

相关单据分录:

array_flip
array_keys
array_merge
array_unique
call_user_func_array

听起来您正在生成的数组的键是无关紧要的。如果是这样的话,你可以做一个简单的合并,然后用内置的PHP函数确定唯一的合并:

$array = array_merge($array1, $array2, $array3);
$unique = array_unique($array);

edit:一个例子:

// Emulate the result of your get_post_meta() call.
$therapie = array(
  array('Massagetherapie'),
  array('Hot stone'),
  array('Massagetherapie'),
);
$array = array();
foreach($therapie as $thera) {
  $array = array_merge($array, $thera);
}
$unique = array_unique($array);
print_r($unique);

PHP的array_unique()将从数组中删除重复的值。

$tester = array();
foreach($therapie as $thera) {
   array_push($tester, $thera);
}
$result = array_unique($tester);
print_r($result);