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 would I merge these arrays to one and delete all the exact double names?
Resulting in something like this:
theArray
(
[0] => Massagetherapie
[1] => Hot stone
)
[SOLVED] the problem was if you do this in a while loop it wont work here my solution, ty for all reply's and good code.: Its run the loop and pushes every outcome in a 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>';
} ?>
The following should do the trick.
$flattened = array_unique(call_user_func_array('array_merge', $therapie));
or the more efficient alternative (thanks to erisco's comment):
$flattened = array_keys(array_flip(
call_user_func_array('array_merge', $therapie)
));
If $therapie's keys are strings you can drop array_unique.
Alternatively, if you want to avoid call_user_func_array, you can look into the various different ways of flattening a multi-dimensional array. Here are a few (one, two) good questions already on SO detailing several different methods on doing so.
I should also note that this will only work if $therapie is only ever a 2 dimensional array unless you don't want to flatten it completely. If $therapie is more than 2 dimensions and you want to flatten it into 1 dimension, take a look at the questions I linked above.
Relevant doc entries:
array_flip
array_keys
array_merge
array_unique
call_user_func_array
It sounds like the keys of the arrays you are generating are insignificant. If that's the case, you can do a simple merge then determine the unique ones with built in PHP functions:
$array = array_merge($array1, $array2, $array3);
$unique = array_unique($array);
edit: an example:
// 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's array_unique() will remove duplicate values from an array.
$tester = array();
foreach($therapie as $thera) {
array_push($tester, $thera);
}
$result = array_unique($tester);
print_r($result);
Related
I have an array like this,
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
I want to find any value with an ">" and replace it with a range().
The result I want is,
array(
1,2,3,4,5,6,7,8,9,10,11,12, '13.1', '13.2', 14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30
);
My understanding:
if any element of $array has '>' in it,
$separate = explode(">", $that_element);
$range_array = range($separate[0], $separate[1]); //makes an array of 4 to 12.
Now somehow replace '4>12' of with $range_array and get a result like above example.
May be I can find which element has '>' in it using foreach() and rebuild $array again using array_push() and multi level foreach. Looking for a more elegant solution.
You can even do it in a one-liner like this:
$array = array(1,2,3,'4>12','13.1','13.2','14>30');
print_r(array_reduce(
$array,
function($a,$c){return array_merge($a,#range(...array_slice(explode(">","$c>$c"),0,2)));},
[]
));
I avoid any if clause by using range() on the array_slice() array I get from exploding "$c>$c" (this will always at least give me a two-element array).
You can find a little demo here: https://rextester.com/DXPTD44420
Edit:
OK, if the array can also contain non-numeric values the strategy needs to be modified: Now I will check for the existence of the separator sign > and will then either merge some cells created by a range() call or simply put the non-numeric element into an array and merge that with the original array:
$array = array(1,2,3,'4>12','13.1','64+2','14>30');
print_r(array_reduce(
$array,
function($a,$c){return array_merge($a,strpos($c,'>')>0?range(...explode(">",$c)):[$c]);},
[]
));
See the updated demo here: https://rextester.com/BWBYF59990
It's easy to create an empty array and fill it while loop a source
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
$res = [];
foreach($array as $x) {
$separate = explode(">", $x);
if(count($separate) !== 2) {
// No char '<' in the string or more than 1
$res[] = $x;
}
else {
$res = array_merge($res, range($separate[0], $separate[1]));
}
}
print_r($res);
range function will help you with this:
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
$newArray = [];
foreach ($array as $item) {
if (strpos($item, '>') !== false) {
$newArray = array_merge($newArray, range(...explode('>', $item)));
} else {
$newArray[] = $item;
}
}
print_r($newArray);
Best way to convert marge array for inner array. Mainly asking if there are any (php) function, as by looping I can esealy achive this.
Example
PHP array:
array(
array('type'=>'ORANGE', 'attribute'=>'sweet'),
array('type'=>'ORANGE', 'attribute'=>'tropical'),
array('type'=>'BANANA', 'attribute'=>'yellow')
);
desired output:
array(
array('type'=>'ORANGE', 'attribute'=>array('sweet','tropical')),
array('type'=>'BANANA', 'attribute'=>array('yellow'))
);
Just loop through the first array and build a new one. Code is not perfomat, but optimal to understand the buisness logic behind
<?php
$arr = array(
array('type'=>'ORANGE', 'attribute'=>'sweet'),
array('type'=>'ORANGE', 'attribute'=>'tropical'),
array('type'=>'BANANA', 'attribute'=>'yellow')
);
$new = array();
foreach($arr as $a) {
$out[$a['type']]['attribute'][] = $a['attribute'];
}
$new = array();
foreach($out as $key=>$val) {
$new[]= array('type'=>$key,$val);
}
unset($out);
echo "<pre>";
var_dump($new);die;
?>
Sorry if it's obvious for you guys, but here what i'm tryiny to do:
I have the following array :
$myArray=Array ( "024848772" ,"0550244954", "0560084252","0559180203","0673466366","021648334" ....);
And I want to have it like this :
Array ( array("024848772"),array("0550244954"),array("0560084252"),array("0559180203"),array("0673466366"),array("021648334") ....);
<?php
$a=array(1,2,3,4,5);
function fun($v) {
return array($v);
}
print_r(array_map("fun",$a));
Loop over the array and add the result to an accumulator wrapping them in an array:
$acc = array();
foreach($myArray as $someString){
$acc[] = array($someString);
}
var_dump($acc);
Example in sandbox here.
Try this code:
$myArray=Array ( "024848772" ,"0550244954", "0560084252","0559180203","0673466366","021648334" );
$arrays = array();
foreach ($myArray as $x)
$arrays[] = array($x);
//print_r($arrays);
Not really seeing the problem. Your original syntax works.
$myArray = Array ( array("024848772"),array("0550244954"),array("0560084252"),array("0559180203"),array("0673466366"),array("021648334"));
var_dump($myArray);
I have this array in php,
$mainArray = array(
array("apple","two", "grren"),
array("samsung","five", "red"),
array("microsoft","one","gray"),
array("apple","nine", "blue"),
array("samsung","ten", "white"),
array("nokia","seven", "yellow")
);
I can easily loop through it and extract all the first entries of each array like this:
foreach($mainArray as $w => $n) {
$whatever = $mainArray[$w][0];
}
I'm trying to count how many entries are the same in the first element of each array, and have a result of something like:
apple (2)
samsung (2)
microsoft (1)
nokia (1)
I'm just not sure what is the correct way to do this.
Thank you in advance.
print_r(
array_count_values(
array_map('array_shift', $mainArray)
)
);
Output (Demo):
Array
(
[apple] => 2
[samsung] => 2
[microsoft] => 1
[nokia] => 1
)
So even I am a big fan of foreach, why did I not use it here?
First of all, to count values in an array, in PHP we have array_count_values. It does the job for us.
So the only problem left was to get all the first items into an array to count them with array_count_values. That is a typical mapping job, and I like mapping, too, next to foreach so I tried if array_map together with array_shift worked - and it did.
However you might want to look for a function called array_column. It's not yet available with PHP itself, but as PHP code in another answer:
$counts = array_count_values(array_column($mainArray, 0));
$count = array();
foreach($mainArray as $array) {
$first = $array[0];
if(!isset($count[$first])) $count[$first] = 0;
$count[$first]++;
}
print_r($count);
Collect every first element of the deep arrays by pushing them into a new array ($result in my example) and then call array_count_values() on that array. Like so:
$mainArray = array(
array("apple","two", "grren"),
array("samsung","five", "red"),
array("microsoft","one","gray"),
array("apple","nine", "blue"),
array("samsung","ten", "white"),
array("nokia","seven", "yellow")
);
$result = array();
foreach( $mainArray as $k => $v )
{
// let's continue if $v is not an array or is empty
if( !is_array( $v ) || empty( $v ) ) continue;
$result[] = $v[ 0 ];
}
var_dump( array_count_values( $result ) );
You can loop through the $mainArray to build a full array/list of values and then use array_count_values() on that:
$firstElements = array();
foreach ($mainArray as $arr) {
$firstElements[] = $arr[0];
}
$counts = array_count_values($firstElements);
Another option would be to loop through $mainArray and insert the value as an index for an array (if it doesn't already exist) and then increment it each time (this will do the same thing as array_count_values() in the end):
$counts = array();
foreach ($mainArray as $arr) {
if (!isset($counts[$arr[0]])) $counts[$arr[0]] = 0;
$counts[$arr[0]]++;
}
You can do it just like this:
foreach($mainArray as $n) {
$count[$n[0]] = isset($count[$n[0]]) ? $count[$n[0]]++ : 1;
}
var_dump($count); //should give you something like
/*
array(4) {
["apple"]=>
int(2)
["samsung"]=>
int(2)
["microsoft"]=>
int(1)
["nokia"]=>
int(1)
}
*/
I have an array which may have duplicate values
$array1 = [value19, value16, value17, value16, value16]
I'm looking for an efficient little PHP function that could accept either an array or a string (whichever makes it easier)
$array2 = ["value1", "value16", "value17"];
or
$string2 = "value1 value16 value17";
and removes each item in array2 or string2 from array1.
The right output for this example would be:
$array1 = [value19]
For those more experienced with PHP, is something like this available in PHP?
you're looking for array_diff
$array1 = array('19','16','17','16','16');
$array2 = array('1','16','17');
print_r(array_diff($array1,$array2));
Array ( [0] => 19 )
For the string version to work, use explode.
Like this:
function arraySubtract($one, $two) {
// If string => convert to array
$two = (is_string($two))? explode(' ',$two) : $two;
$res = array();
foreach (array_diff($one, $two) as $key => $val) {
array_push($res, $val);
}
return $res;
}
This allso returns an array with key = 0....n with no gaps
Test with this:
echo '<pre>';
print_r(arraySubtract(array(1,2,3,4,5,6,7), array(1,3,7)));
print_r(arraySubtract(array(1,2,3,4,5,6,7), "1 3 7"));
print_r(arraySubtract(array("val1","val2","val3","val4","val5","val6"), array("val1","val3","val6")));
print_r(arraySubtract(array("val1","val2","val3","val4","val5","val6"), "val1 val3 val6"));
echo '</pre>';