PHP merge array (s) and remove double values

WP outputs an array:

$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 ) 

How to combine these arrays with one and remove all exact duplicate names?

Result:

theArray
(
[0] => Massagetherapie 
[1] => Hot stone
)

The [SOLVED] problem was that if you do this in a while loop, then my solution will not work here, for the answer and the good code: start the loop and pop each result in the array.

<?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>';
} ?>                 
+3
source share
4 answers

The following should do the trick.

$flattened = array_unique(call_user_func_array('array_merge', $therapie));

or more efficient alternative (thanks erisco comment):

$flattened = array_keys(array_flip(
    call_user_func_array('array_merge', $therapie)
));

If the keys $therapieare strings, you can opt out array_unique.

, call_user_func_array, . (one, ) , SO .

, , $therapie , . $therapie , 1 , , .

:

array_flip
array_keys
array_merge
array_unique
call_user_func_array

+4

, . , merge, unique PHP:

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

: :

// 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);
+4

PHP array_unique () will remove duplicate values ​​from the array.

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

All Articles