Unique php multidimensional array and sort by occurrence - php

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

Related

Replace array value with more than one values

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

PHP array comparision error

I have 2 SELECT statement in my PHP. Both the select statements fetch data from two different DB. The fetched data is saved in PDO Assoc Array. The problem is when I want to compare those two arrays to find that if the column 'id' exist in both arrays or not. If it exists then ignore it. If it's a unique id then save it into a third array. But I found some problems in my Logic Below
And after running the below code I am getting a couple of error:
1: Array to string conversion
2: duplicate key value violates unique constraint
$arr1 = $msql->fetchAll(PDO::FETCH_ASSOC);
$array1 = array();
foreach($arr1 as $x){
$array1[] = $x['id'];
}
$arr2 = $psql->fetechAll(PDO::FETCH_ASSOC);
$array2 = array();
foreach($arr2 as $y){
$array2[] = $y['id'];
}
$finalarray = array();
for ($i = 0; $i < count($arr1); $i++){
if(count(array_intersect($array1,$array2)) <= 1){// is the count of id is 1 or less save that whole row in the $finalarray
$finalarray = $arr1[$i]; // saving the unique row.
}
else{
continue;
}
}
All I am trying to get the unique row of data array() after comparing their id column.
You can use in_array() function as both arrays are index array.
$finalarray = array();
for ($i = 0; $i < count($arr1); $i++){
if(count(array_intersect($array1,$array2)) <= 1){// is the count of id is 1 or less save that whole row in the $finalarray
$finalarray = $arr1[$i]; // saving the unique row.
}
else{
continue;
}
}
make change in code:
$finalarray = array();
for ($i = 0; $i < count($arr1); $i++){
if(!in_array($array1[$i], $array2)){
$finalarray[] = $array1[$i]; // saving the unique row.
}
}
You can simply use array_intersect() to get common values between two array. for difference, can use array_diff()
$array1 = [1,2,3,4,5,6,7];
$array2 = [2,4,6];
//array_intersect — Computes the intersection of arrays
$result = array_intersect($array1, $array2);
print_r($result);
//array_diff — Computes the difference of arrays
$result = array_diff($array1, $array2);
print_r($result);
DEMO
Rather than using 3 different arrays to get unique ids, you can do it by using one array. Make changes to your code as below:
$finalarray = array();
$arr1 = $msql->fetchAll(PDO::FETCH_ASSOC);
foreach($arr1 as $x){
if (!in_array($x['id'],$finalarray)) { // check id is already stored or not
$finalarray[] = $x['id'];
}
}
$arr2 = $psql->fetechAll(PDO::FETCH_ASSOC);
foreach($arr2 as $y){
if (!in_array($y['id'],$finalarray)) { // check id is already stored or not
$finalarray[] = $y['id'];
}
}
Maybe you should make sure which array is larger before your loop ;
Or using array_diff:
$finalarray = array_diff($array1 , $array2) ?? [];
$finalarray = array_merge( array_diff($array2 , $array1) ?? [], $finalarray );

array_intersection parital matches in two arrays

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
)

Nested loops and array formation

Suppose that I start with an array that looks like:
$array_1 = array(array(1,2,3), array(2,4,5), array(3,6,7));
For simplicity, assume that I have a rule that says: delete the first subarray and then delete the first elements of the remaining subarrays. This would yield the result:
$new_array = array(array(4,5), array(6,7))
Then assume I expand the problem to larger arrays like:
$array_2 = array(array(1,2,3,4), array(2,3,4,5), array(3,4,5,6), array(4,5,6,7));
I have the same rule here - delete first subarray and then delete first elements of the remaining subarrays. BUT this rule must be continued until the smallest subarray contains only two elements (as in the first example). So that in stage one of the process, my new array would look like:
$new_array_s1 = array(array(3,4,5), array(4,5,6), array(5,6,7));
But in the final stage, the completed array would look like:
$new_array_s2 = array(array(5,6), array(6,7));
For context, here is my code for the $array_1 example:
<?php
$array_1 = array(array(1,2,3), array(2,4,5), array(3,6,7));
$array_shell = $array_1;
unset($array_shell[0]);
$array_size = count($array_shell);
$i = 0;
$cofactor = array();
while($i < $array_size) {
$el_part_[$i] = $array_1[$i];
unset($el_part_[$i][0]);
$el_part_[$i] = array_values($el_part_[$i]);
array_push($cofactor, $el_part_[$i]);
++$i;
}
echo '<pre>',print_r($cofactor,1),'</pre>';
?>
My Question: How can I generalise this code to work for N sized arrays?
You don't need a complicated code .. Just loop and use array_shift
Example:
print_r(cleanUp($array_1));
Function
function cleanUp($array) {
array_shift($array);
foreach($array as $k => $var) {
is_array($var) && array_shift($array[$k]);
}
return $array;
}
See Live DEMO
$num = count($array_1);
for($i=0;$i<=$num;$i++)
{
if($i==0)
unset($array_1[$i]);
else unset($array_1[$i][0]);
}
Building off of Baba's answer, to work with N element arrays (assuming each array contains the same number of elements):
<?php
$array_1 = array(array(1,2,3,4), array(2,4,5,6), array(3,6,7,8));
$array = $array_1;
while(count($array[0]) > 2)
$array = cleanUp($array);
print_r($array);
function cleanUp($array) {
array_shift($array);
foreach($array as $k => $var) {
is_array($var) && array_shift($array[$k]);
}
return $array;
}
This will keep reducing until the sub-arrays have only 2 elements.
-Ken

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

Categories