find duplicate value in multi-dimensional array - php

From a function I am given a multidimensional array like this:
array(
[0] => array(
[0] => 7,
[1] => 18
),
[1] => array(
[0] => 12,
[1] => 7
),
[2] => array(
[0] => 12,
[1] => 7,
[2] => 13
)
)
I need to find duplicate values in the 3 arrays within the main array. For example, if value 7 repeats in the 3 arrays, return 7.

<?php
$array = array(array(7,18), array(12,7), array(12, 7, 13));
$result = array();
$first = $array[0];
for($i=1; $i<count($array); $i++){
$result = array_intersect ($first, $array[$i]);
$first = $result;
}
print_r($result);//7
?>

use my custom function
function array_icount_values($arr,$lower=true) {
$arr2=array();
if(!is_array($arr['0'])){$arr=array($arr);}
foreach($arr as $k=> $v){
foreach($v as $v2){
if($lower==true) {$v2=strtolower($v2);}
if(!isset($arr2[$v2])){
$arr2[$v2]=1;
}else{
$arr2[$v2]++;
}
}
}
return $arr2;
}
$arr = array_icount_values($arry);
echo "<pre>";
print_r($arr);
exit;
OUPUT
Array
(
[7] => 3
[18] => 1
[12] => 2
[13] => 1
)
hope this will sure help you.

$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
use this code
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;

You will need to loop through the first array, and for each value in it, see if it is in_array().
$findme = array();
foreach ($array[0] as $key => $value)
{
if (in_array ($value, $array[1]) && in_array ($value, $array[2]))
{
$findme[] = $value;
}
}
// $findme will be an array containing all values that are present in all three arrays (if any).

Related

Sum like values in Multi-Dimensional array php

I need to sum the values in element 1 of my array where the values in element 0 are duplicate.
Here's a small piece of my array
Array
(
[0] => 3
[1] => 1
)
Array
(
[0] => 3
[1] => 2
)
Array
(
[0] => 3
[1] => 128
)
Array
(
[0] => 39
[1] => 4
)
The results i'm expecting to see
Array
(
[0] => 3
[1] => 131
)
Array
(
[0] => 39
[1] => 4
)
I'm still really new to PHP so any help is greatly appreciated.
You can use a combination of array_intersect, array_column and array_sum to only iterate twice. (One for each unique column 0 value).
$col0 = array_column($arr, 0);
$col1 = array_column($arr, 1);
Foreach(array_unique($col0) as $val){
$res[] = [$val, array_sum(array_intersect_key($col1, array_intersect($col0,[$val])))];
}
Var_dump($res);
https://3v4l.org/gKb5b
The way I've done it is made sure all duplicates where put in the same array.
// Your data
$sample = [[3, 1],[3, 2],[3, 128],[39, 4]];
foreach($sample as $array){
$tmp[$array[0]][] = $array[1];
}
# Output: {"3":[1,2,128],"39":[4]}
Now sum the arrays, and put it back to the structure it originally was.
foreach($tmp as $k => $v){
$new[] = [$k, array_sum($v)];
}
# Output: [[3,131],[39,4]]
But many roads lead to Rome.
Try this code. It may help you.
$array = array(["0" => 3, "1" => 1] , ["0" => 3, "1" => 2], ["0" => 3, "1" => 128], ["0" => 39, "1" => 4]);
$finalArray = [];
foreach($array as $a) {
$finalArray[$a[0]][0] = $a[0];
$finalArray[$a[0]][1] = !isset($finalArray[$a[0]][1]) ? $a[1] : $finalArray[$a[0]][1] + $a[1];
}
echo '<pre>';
print_r($finalArray);
exit;
You could do something like this. I have separated into two foreach. Hope it helps.
<?php
$a = [[3,1],[3,2],[3,128],[39,4]];
$result=[];
$temp = [];
foreach($a as $line) {
$temp[$line[0]] += $line[1];
}
foreach($temp as $k => $value) {
$result[]=[$k ,$value];
}
$data =
[
[3,1],
[3,2],
[3,128],
[39,4]
];
foreach($data as $item)
$sums[$item[0]] = ($sums[$item[0]] ?? 0) + $item[1];
$result = array_map(null, array_keys($sums), $sums);
var_export($result);
Output:
array (
0 =>
array (
0 => 3,
1 => 131,
),
1 =>
array (
0 => 39,
1 => 4,
),
)
$arr = [ [ 3, 1],[ 3, 2 ],[ 3, 128], [ 39, 4]];
$sum = [];
foreach($arr as $value) {
$sum[$value[0]][] = $value[1];
}
foreach($sum as $key=>$value ) {
$result[] = [ $key, array_sum($value)];
}
Output:
Array
(
[0] => Array
(
[0] => 3
[1] => 131
)
[1] => Array
(
[0] => 39
[1] => 4
)
)

converting different indexes values in arrays to another array in php

I have an array as:
Array
(
[0] => Array
(
[0] => A
[1] => B
)
[1] => C
[2] => Array
(
[0] => D
[0] => E
)
)
and I want to convert it like:
Array
(
[0] => Array
[0] => A
[1] => B
[2] => C
[3] => D
[4] => E
)
i.e I want all the values in the first array (irrespective of their indexes) to be aligned in the second array.
You need to write a custom script which merge arrays by your logic.
Example:
<?php
$a = [
['A', 'B'],
'C',
['D', 'E']
];
$result = [];
foreach ($a as $v) {
if (is_array($v))
$result = array_merge($result, $v);
else
$result[] = $v;
}
print_r([$result]);
You can user this :
$array = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)),0);
I have copied from here how Turning multidimensional array into one-dimensional array
Please try with below code:
$arr = array(
0 => array("A", "B"),
1 => "C",
2 => array("D", "E"),
);
$result = array();
$response = arrayIndex($arr, $result);
function arrayIndex($arr, $result){
foreach ($arr as $key => $value) {
if(is_array($value)){
$result = $this->arrayIndex($value, $result);
} else {
array_push($result, $value);
}
}
return $result;
}
NOTE: This function will convert n level of array elements into a single level array.

How to remove all items of array except specific one?

I have a variable which is containing these nested arrays:
echo $var;
/* Output:
Array(
[0] => Array
(
[id] => 1
[box] => 0
)
[2] => Array
(
[id] => 2
[box] => 0
)
[3] => Array
(
[id] => 3
[box] => 1
)
) */
Now I want to remove all items of array above except $numb = 2; (the value of id). I mean I want this output:
echo newvar;
/* Output:
Array(
[2] => Array
(
[id] => 2
[box] => 0
)
) */
How can I do that?
Actually I can do a part of it by using if statement and array_shift() function:
foreach($var as $key => $val) {
if($val["id"] != 2) {
array_shift($var);
}
}
But the output of code above isn't want I need.
You can use a slightly different loop.
foreach ($var as $item) {
if ($item['id'] == 2) {
$newvar = $item;
break;
}
}
You could also use array_filter
$id = 2;
$newvar = array_filter($var, function($x) use ($id) { return $x['id'] == $id; });
but it would most likely be less efficient as it would have to check every element of the array.
I'm wondering how much context would help us with answering your question... Here is an answer to what you asked:
$newArray = array($var[2]);
You could just make a new array:
$oldArray = array(0 => 'a', 1 => 'b', 2 => 'c', 3=> 'd');
$index = 2;
$newArray = array($index => $oldArray[$index]);
// or even
$newArray = [$index => $oldArray[$index]];
If you don't need to preserve the index you can just do:
$newArray = [$oldArray[$index]];
array_reduce() would also do the job:
$array = [
['id' => 1, 'box' => 0],
['id' => 2, 'box' => 0],
['id' => 3, 'box' => 1]
];
$id = 2;
$result = array_reduce ($array, function ($carry, $item) use ($id) {
if ( $item['id'] === $id )
$carry[$item['id']] = $item;
return $carry;
}, []);

Put a named key before numeric keys in array

Need to compare two arrays
Working example
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
Array1 Output:
Array ( [a] => green [0] => red [1] => blue )
When I do Like this
$array1 = array();
while($fetch = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$array1[] = $fetch['color'];
}
I get this output:
Array ([0] => gren [1] => red [2] blue
How do I add the "a" to the array and make the first color be number zero?
This adding the "a" but it gets the zero number
array_unshift($array1,"a");
LIKE
Array ( [0] => a [1] => green
I want this
Array ( [a] => green [0]
I'm not sure why you want to do this, but here's how:
$array1 = array();
while ($fetch = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
if (empty($array1)) {
$array1['a'] = $fetch['color'];
} else {
$array1[] = $fetch['color'];
}
}
$arr = array(0 => 'green', 1 => 'red', 2 => 'blue');
$res = array_merge(array('a' => current($arr)), array_slice($arr, 1));
You can do with array_merge and array_shift function:
$arr = array(0 => 'green', 1 => 'red', 2 => 'blue');
$new = array_merge(array('a' => array_shift($arr)), $arr);
Demo: http://codepad.org/osifrZKZ

How can I merge PHP arrays?

I have two arrays of animals (for example).
$array = array(
array(
'id' => 1,
'name' => 'Cat',
),
array(
'id' => 2,
'name' => 'Mouse',
)
);
$array2 = array(
array(
'id' => 2,
'age' => 321,
),
array(
'id' => 1,
'age' => 123,
)
);
How can I merge the two arrays into one by the ID?
#Andy
http://se.php.net/array_merge
That was my first thought but it doesn't quite work - however array_merge_recursive might work - too lazy to check right now.
This does what Erik suggested (id no. as array key) and merges vlaues in $array2 to $results.
$results = array();
foreach($array as $subarray)
{
$results[$subarray['id']] = array('name' => $subarray['name']);
}
foreach($array2 as $subarray)
{
if(array_key_exists($subarray['id'], $results))
{
// Loop through $subarray would go here if you have extra
$results[$subarray['id']]['age'] = $subarray['age'];
}
}
First off, why don't you use the ID as the index (or key, in the mapping-style array that php arrays are imo)?
$array = array(
1 => array(
'name' => 'Cat',
),
2 => array(
'name' => 'Mouse',
)
);
after that you'll have to foreach through one array, performing array_merge on the items of the other:
foreach($array2 as $key=>$value) {
if(!is_array($array[$key])) $array[$key] = $value;
else $array[$key] = array_merge($array[key], $value);
}
Something like that at least. Perhaps there's a better solution?
<?php
$a = array('a' => '1', 'b' => array('t' => '4', 'g' => array('e' => '8')));
$b = array('c' => '3', 'b' => array('0' => '4', 'g' => array('h' => '5', 'v' => '9')));
$c = array_merge_recursive($a, $b);
print_r($c);
?>
array_merge_recursive — Merge two or more arrays recursively
outputs:
Array
(
[a] => 1
[b] => Array
(
[t] => 4
[g] => Array
(
[e] => 8
[h] => 5
[v] => 9
)
[0] => 4
)
[c] => 3
)
#Andy
I've already looked at that and didn't see how it can help merge multidimensional arrays. Maybe you could give an example.
#kevin
That is probably what I will need to do as I think the code below will be very slow.
The actual code is a bit different because I'm using ADOdb (and ODBC for the other query) but I'll make it work and post my own answer.
This works, however I think it will be very slow as it goes through the second loop every time:
foreach($array as &$animal)
{
foreach($array2 as $animal2)
{
if($animal['id'] === $animal2['id'])
{
$animal = array_merge($animal, $animal2);
break;
}
}
}
foreach ($array as $a)
$new_array[$a['id']]['name'] = $a['name'];
foreach ($array2 as $a)
$new_array[$a['id']]['age'] = $a['age'];
and this is result:
[1] => Array
(
[name] => Cat
[age] => 123
)
[2] => Array
(
[name] => Mouse
[age] => 321
)
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
With PHP 5.3 you can do this sort of merge with array_replace_recursive()
http://www.php.net/manual/en/function.array-replace-recursive.php
You're resultant array should look like:
Array (
[0] => Array
(
[id] => 2
[name] => Cat
[age] => 321
)
[1] => Array
(
[id] => 1
[name] => Mouse
[age] => 123
)
)
Which is what I think you wanted as a result.
I would rather prefer array_splice over array_merge because of its performance issues, my solution would be:
<?php
array_splice($array1,count($array1),0,$array2);
?>
$new = array();
foreach ($array as $arr) {
$match = false;
foreach ($array2 as $arr2) {
if ($arr['id'] == $arr2['id']) {
$match = true;
$new[] = array_merge($arr, $arr2);
break;
}
}
if ( !$match ) $new[] = $arr;
}

Categories