PHP:Check duplicate values in all nested array - php

I would like to find out a duplicate value in the all nested arrays within an array.
At the moment my array is something like that.
Array $bigarray = Array (
[431] => Array (
[0] => orange
[1] => apple
[2] => pine
)
[440] => Array (
[0] => orange
[1] => lilly
)
[444] => Array (
[0] => orange
[1] => pine
)
)
I would like to extract only orange which is in all
arrays('431','440','444').
Woudl you give me some idea...?
Thanks in advance.

You can use array_intersect():
$intersected = null;
foreach ($bigarray as $arr) {
$intersected = $intersected ? array_intersect($arr, $intersected) : $arr;
if (!$intersected) {
break; // no reason to continue
}
}
print_r($intersected);
Array
(
[0] => orange
)

$inAllChunks = call_user_func_array('array_intersect',(array_values($bigarray)));
var_dump($inAllChunks);

$output = null;
foreach ( $bigarray as $array ) {
if ( is_null($output) ) {
$output = $array;
continue;
}
$output = array_intersect($output, $array);
if ( empty($output) ) {
break;
// there are no common elements in the array
}
}
var_dump$(output);

From the documentation.
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
http://www.php.net/manual/en/function.array-intersect.php

Related

Merging 3 arrays in PHP

I have 3 arrays as below.
$array1 = Array
(
[0] => 05/01
[1] => 05/02
)
$array2 =Array
(
[0] => ED
[1] => P
)
$array3 =Array
(
[0] => Mon
[1] => Tue
)
I want to merge these 3 arrays as below $result_array. I have written a code as below. But It gave a empty array.
$result_array =Array
(
[0] => Array
(
[0] => 05/01
[1] => ED
[2] => Mon
)
[1] => Array
(
[0] => 05/02
[1] => P
[2] => Tue
)
)
Code:
for($z=0; $z<count($array1); $z++){
$all_array[$z][] = array_merge($array1[$z],$array2[$z] );
$all_array2[$z] = array_merge($all_array[$z],$array3[$z] );
}
Please help me to do this.
Simply foreach over the first array and use the index as the key to the other arrays.
foreach ( $array1 as $idx => $val ) {
$all_array[] = [ $val, $array2[$idx], $array3[$idx] ];
}
Remember this will only work if all 3 arrays are the same length, you might like to check that first
You can simply walk through the first array with a foreach loop then access the corresponding arrays and combine the results into one big array. This will only work if the arrays are the same length so it's worth checking that before to stop any errors. Something like this:
<?php
$arr1 = ['05/01', '05/02'];
$arr2 = ['ED', 'P'];
$arr3 = ['Mon', 'Tue'];
$combined = [];
if (count($arr1) != count($arr2) || count($arr1) != count($arr3))
die("Array lengths do not match!");
foreach ($arr1 as $key => $val) {
$combined[] = [$val, $arr2[$key], $arr3[$key]];
}
var_dump($combined);
You can see an eval.in of this working here - https://eval.in/833893
Create an sample array and push to each array value with respective key
$sample = array();
for($z=0; $z<count($array1); $z++){
$sample[]=array($array1[$z],$array2[$z],$array3[$z]);
}
print_r($sample);
Out put is
Array ( [0] => Array (
[0] => 05/01
[1] => ED
[2] => Mon
)
[1] => Array (
[0] => 05/02
[1] => P
[2] => Tue
)
)
this work for n of arrays and dynamic length of array
function mergeArrays(...$arrays)
{
$length = count($arrays[0]);
$result = [];
for ($i=0;$i<$length;$i++)
{
$temp = [];
foreach ($arrays as $array)
$temp[] = $array[$i];
$result[] = $temp;
}
return $result;
}
$x = mergeArrays(['05/01' , '05/02'] , ['ED' , 'P'] , ['Mon' , 'Tus']);
$y = mergeArrays(['05/01' , '05/02' , 'X'] , ['ED' , 'P' , 'Y'] , ['Mon' , 'Tus' , 'Z'] , ['A' , 'B' , 'C']);
var_dump($x);
var_dump($y);
function merge($file_name, $titles, $description)
{
$result = array();
foreach($file_name as $key=>$name )
{
$result[] = array( 'file_name' => $name, 'title' => $titles[$key],
'description' => $description[ $key ] );
}
return $result;
}
$array1 = Array
(
'05/01',
'05/02'
);
$array2 = Array
(
'ED',
'P'
);
$array3 =Array
(
'Mon',
'Tue'
);
$result_array = array();
foreach ($array1 as $key=>$val)
{
$result_array[$key] = array($array1[$key],$array2[$key],$array3[$key]);
}
echo "<PRE>"; print_r($result_array);

Handling multi-dimensional PHP Array

I have arrays of fonts with their name and weight e.g.
print_r($fontarray1);
Array (
[font] => Open+Sans
[weight] => normal
)
print_r($fontarray2);
Array (
[font] => Open+Sans
[weight] => bold
)
print_r($fontarray3);
Array (
[font] => Lato
[weight] => bolditalic
)
I have many arrays of fonts $fontarray1, $fontarray2, $fontarray3.. I want to make one final array of fonts and their weights.. for example, if "Open+Sans" is already in the final array, it should not be added, but if "Open+Sans" is in final Array with a different "weight" then only the "weight" should be added alongwith the "Open+Sans" key.. the expected result should be something like:
Array (
[font] => Oen+Sans
[weight] => Array (
[0] => normal
[1] =>bold
)
[font] => Lato
[weight] => Array (
[0] => bolditalic
)
)
I tried something like below, but confused on how to add another array within one array..:
$final_arr = Array();
if (!in_array($fontarray1['font'], $final_arr)) {
$final_arr []= $fontarray1['font'];
} else {
// already in array, lets check font weight
}
}
any help or thought would be highly appreciated. cheers
First
Use array_merge
<?php
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>
Second
Use array_unique
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
Look` like structure like this can be usefull for you:
Array(
"fontName" => Array(
[weight] => Array(
[0] => "normal"
)
)
)
And your function would be like
$final_arr = Array();
$fontName = $fontarray1['font'];
$fontWeight = $fontarray1['weight'];
if (!isset($final_arr[$fontName])) {
$final_arr[$fontName] = array('weight' => $fontWeight);
} else {
$final_arr[$fontName]['weight'][] = $fontWeight;
}
You're just trying to add $fontarray1 to $final_arr?
$final_arr[] = $fontarray1
Creating a multidimensional array:
$theArray = array();
$theArray[] = array('key1'=>'val1', 'key2'=>'val2'); // creates a subarray

php array find duplicates, sum them up & delete duplicates

i have an array:
Array
(
[0] => Array
(
[setid] => 2
[income] => 100
)
[1] => Array
(
[setid] => 2
[income] => 120
)
[2] => Array
(
[setid] => 3
[income] => 700
)
)
i need to find entrys with the same setid, sum their income up and delete duplicate entrys - in the end it should look like this:
Array
(
[0] => Array
(
[setid] => 2
[income] => 220
)
[1] => Array
(
[setid] => 3
[income] => 700
)
)
does someone know a sophosticated solution for my problem or do i have to take the long road and do every step manually?
thanks and greetings
Just create a new array which you make fast adressable by using the setid as key. And reindex the array at the end.
$result = array();
foreach ($array as $val) {
if (!isset($result[$val['setid']]))
$result[$val['setid']] = $val;
else
$result[$val['setid']]['income'] += $val['income'];
}
$result = array_values($result); // reindex array
This should work:
$values = array();
foreach($array as $val) {
if(isset($values[$val['setid']])) {
$values[$val['setid']] += $val['income'];
} else {
$values[$val['setid']] = $val['income'];
}
}
//all values are now in $values array, keys are setid and values are income
Write your own function, that's no long road at all.
$result = array_reduce($originalArray, function($memo, $item){
isset($memo[$item['setid']])
? $memo[$item['setid']] = $item['income']
: $memo[$item['setid']] += $item['income'];
return $memo;
}, []);
You should use the array_unique function that php's official site offers.
An example:
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
Output:
Array
(
[a] => green
[0] => red
[1] => blue
)
To sum the duplicated values you can use the array_count_values function:
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Output would be:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)

How can I group arrays into one array in php?

I would like to convert / form the following arrays as example:
Array ( [product_category] => for-women ) Array ( [brand] => 7-diamonds ) Array ( [size] => 12 ) Array ( [color] => 882536 )
Into one array that just merges each array pair and put them altogether :
Array ( [product_category] => for-women [brand] => 7-diamonds [size] => 12 [color] => 882536 )
I tried array_merge and it didn't work. The array out put in my code is from $_SESSION which returns an array (a pair key=> value) like this:
foreach($_SESSION as $k => $v) {
if (strstr($k, 'saved_query_') == true) {
$saved = array_merge($v);
}
}
So I get each array by looping through session which has a query, the result is array pair, I want to combine all pairs found (Do not know how to use array_merge in that case).
I tried array_combine and array_merge they do not seem like the functions I need based on php manual:
array_combine — Creates an array by using one array for keys and another for its values
Which I do not want to do, I just want to copy/move small arrays in one array, without changing any pairing/key/value.
You can try using array_merge
$array0 = Array ( "product_category" => "for-women" );
$array1 = Array ( "brand" => "7-diamonds" ) ;
$array2 = Array ( "size" => "12" ) ;
$array3 = Array ( "color" => "882536" );
$array = array_merge($array0,$array1,$array2,$array3);
print_r($array);
Output
Array ( [product_category] => for-women [brand] => 7-diamonds [size] => 12 [color] => 882536 )
See Demo
* ----- Update ----- *
If you are looking through a session
$_SESSION = Array();
$_SESSION[0] = Array("product_category" => "for-women");
$_SESSION[1] = Array("brand" => "7-diamonds");
$_SESSION[2] = Array("size" => "12");
$_SESSION[3] = Array("color" => "882536");
$final = array();
foreach ( $_SESSION as $key => $value ) {
$final = array_merge($final, $value);
}
print_r($final);
Use array_merge_recursive() :
$result = array_merge_recursive($ar1, $ar2 [, array $...]);
Example: http://codepad.viper-7.com/Yr0LTb
Use array_merge instead.
$ret = array_merge($arr1, $arr2, $arr3);
With your code, you should do:
$saved = array_merge($saved, $v);
You should have a look at the array_merge() function in PHP: http://php.net/manual/en/function.array-merge.php
Simply use as follows:
$array1 = Array ( [product_category] => for-women );
$array2 = Array ( [brand] => 7-diamonds );
$array3 = Array ( [size] => 12 );
$array4 = Array ( [color] => 882536 );
$combined = array_merge($array1, $array2, $array3, $array4);

Create an array from 2 other arrays

$arrayA = Array (
[0] => 1,
[1] => 2,
[2] => 4
)
$arrayB = Array (
[1] => Dog,
[2] => Cat,
[3] => Cow,
[4] => Duck
)
How do I create an $arrayC that takes the value from the above 2 arrays:
$arrayC = Array (
[1] => Dog,
[2] => Cat,
[4] => Duck
)
Theoretically, it's something like this:
$arrayC = Array (
[$arrayA[0]] => $arrayB[$arrayA[0]],
[$arrayA[1]] => $arrayB[$arrayA[1]],
[$arrayA[2]] => $arrayB[$arrayA[2]]
)
Thanks.
You can do this in elegant way without foreach (Demo):
$arrayC = array_intersect_key($arrayB, array_flip($arrayA));
See array_intersect_key[Docs] and array_flip[Docs]
$arrayC = array();
foreach ($arrayA as $key) {
if (isset($arrayB[$key])) {
$arrayC[$key] = $arrayB[$key];
}
}
No need to write the foreach loop yourself:
//get only the keys that are in both
$arrayA = array_intersect_key(array_fill_keys($arrayA , true), $arrayB);
$arrayB = array_intersect_key($arrayB, $arrayA);
//combine the arrays
$arrayC = array_combine(array_keys($arrayA), $arrayB);
foreach($arrayA as $i => $key) {
$arrayC[$key] = $arrayB[$arrayA[$i]];
}
$arrayC will be:
Array ( [1] => Dog [2] => Cat [4] => Duck )
You can try to do something like this :-
foreach ($arrayA as $number)
{
if(isset($arrayB[$number])
{
$arrayC[$number] = $arrayB[$number];
}
}

Categories