array_intersection parital matches in two arrays - php

I have 2 arrays:
$array1 = array("dog","cat","butterfly")
$array2 = array("dogs","cat","bird","cows")
I need to get all partial matches from $array2 compared to $array1 like so:
array("dog","cat")
So I need to check if there are partial word matches in $array2 and output new array with $array1 keys and values.
array_intersection only outputs full matches
Thanks

Try this,
$array1 = array("dog","cat","butterfly");
$array2 = array("dogs","cat","bird","cows");
function partial_intersection($a,$b){
$result = array();
foreach($a as $v){
foreach($b as $val){
if( strstr($val,$v) || strstr($v,$val) ){ $result[] = $v; }
}
}
return $result;
}
print_r(partial_intersection($array1,$array2));

Some more way to get the same result
<?php
$array1 = array("dog","cat","butterfly");
$array2 = array("dogs","cat","bird","cows");
// Array output will be displayed from this array
$result_array = $array1;
// Array values are compared with each values of above array
$search_array = $array2;
print_r( array_filter($result_array, function($e) use ($search_array) {
return preg_grep("/$e/",$search_array);
}));
?>
Output
[akshay#localhost tmp]$ php test.php
Array
(
[0] => dog
[1] => cat
)

Related

Unique php multidimensional array and sort by occurrence

I have a PHP multiD array like:-
$a = array($arrayA, $arrayB, $arrayA, $arrayC, $arrayC, $arrayA...........)
how can I get a resulting array which have distinct elements from this array and sorted with the more occurrence first like:-
array( $arrayA, $arrayB, $arrayC)
because array $arrayA was 3 times in first array so it comes first in resulting array.
I have tried :-
$newArray = array();
$count = count($a);
$i = 0;
foreach ($a as $el) {
if (!in_array($el, $newArray)) {
$newArray[$i] = $el;
$i++;
}else{
$oldKey = array_search($el, $newArray);
$newArray[$oldKey+$count] = $el;
unset($newArray[$oldKey]);
}
}
krsort($newArray);
This is perfectly working but this is very lengthy process because my array has thousands of elements. Thanks in advance for your help.
Try like this :-
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
Like #saravanan answer but result sorted:-
<?php
$input = [['b'],['a'],['b'],['c'],['a'],['a'],['b'],['a']];
$result = array_count_values( array_map("serialize", $input));
arsort($result,SORT_NUMERIC);
$result = array_map("unserialize",array_keys($result));
print_r($result);

Display array_key from PHP array?

Here I am Having an Issue:
I have two arrays like the following:
$array1 = array('1','2','1','3','1');
$array2 = array('1','2','3'); // Unique $array1 values
with array2 values i need all keys of an array1
Expected Output Is:
1 => 0,2,4
2 => 1
3 => 3
here it indicates array2 value =>array1 keys
Just use a loop:
$result = array();
foreach ($array1 as $index => $value) {
$result[$value][] = $index;
}
If you pass array_keys a 2nd parameter, it'll give you all the keys with that value.
So, just loop through $array2 and get the keys from $array1.
$result = array();
foreach($array2 as $val){
$result[$val] = array_keys($array1, $val);
}
The following code will do the job. It will create a result array in which the attribute val will contain the value that is searched in array and keys attribute will be an array that contains the found keys. Based on your values following is an example:
$array1 =array('1','2','1','3','1');
$array2 =array('1','2','3');
$results = array();
foreach ($array2 as $key2=>$val2) {
$result = array();
foreach ($array1 as $key1=>$val1 ) {
if ($val2 == $val1) {
array_push($result,$key1);
}
}
array_push($results,array("val"=>$val2,keys=>$result ));
}
echo json_encode($results);
The result will be:
[{"val":"1","keys":[0,2,4]},
{"val":"2","keys":[1]},
{"val":"3","keys":[3]}]

How do I select last array per key in a multidimensional array

Given the following php array
$a = array(
array('a'=>'111','b'=>'two','c'=>'asdasd'),
array('a'=>'111','b'=>'one','c'=>'sdvsdfs'),
array('a'=>'111','b'=>'three','c'=>'vbndfgn'),
array('a'=>'222','b'=>'nine','c'=>'dfhfnd')
);
how can I return only the last array per array key 'a'?
Desired result:
$new = array(
array('a'=>'111','b'=>'three','c'=>'vbndfgn'),
array('a'=>'222','b'=>'nine','c'=>'dfhfnd')
);
If I were you, I'd try to store it in a better format that makes retrieving it a bit easier. However, if you are stuck with your format, then try:
$a = array(
array('a'=>'111','b'=>'two','c'=>'asdasd'),
array('a'=>'111','b'=>'one','c'=>'sdvsdfs'),
array('a'=>'111','b'=>'three','c'=>'vbndfgn'),
array('a'=>'222','b'=>'nine','c'=>'dfhfnd')
);
$tmp = array();
foreach ($a as $value) {
$tmp[$value['a']] = $value;
}
$new = array_values($tmp);
print_r($new);

PHP merge array(s) and delete 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 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);

Removing all instances of items from array

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>';

Categories