matching sub arrays on array and count them - php

i am having an array
Array
(
[1] => Array
(
[0] => 1
[1] => 3
)
[2] => Array
(
[0] => 1
[1] => 2
)
[3] => Array
(
[0] => 1
[1] => 3
)
)
and i need to find the common subarrays
In the above example array 1 and 3 have the common sub array
(
[0] => 1
[1] => 3
)
So the final array must be
Array
(
[1] => Array
(
[0] => 1
[1] => 3
)
[2] => Array
(
[0] => 1
[1] => 2
)
)
But i need to count the common values some how.
Any suggestion.

I wouldn't use this for production code, but here's a quick & somewhat clever way to do it:
$arrays = array(array(1,3), array(1,2), array(1,3)); // Your example data
$serialized = array_map('serialize', $arrays);
$counts = array_count_values($serialized);
foreach ($counts as $data => $count) {
echo "$count: " . print_r(unserialize($data), true);
}

Just compare each element of array with other assuming them as a linear array but use array_diff to compare each element. If they are different copy the element or array index into another array

To isolate unique rows, use the SORT_REGULAR flag with array_unique().
To acquire the number of duplicated rows, subtract the unique count from the initial count.
Code: (Demo)
$array = [[1, 3], [1, 2], [1, 3]];
$count = count($array);
$unique = array_unique($array, SORT_REGULAR);
echo "Number of duplicated rows: " . ($count - count($unique));

Related

php - set values as index in array

This is my array:
Array
(
[0] => Array
(
[0] => Q1
[1] => 100
)
[1] => Array
(
[0] => Q2
[1] => 200
)
[2] => Array
(
[0] => Q3
[1] => 300
)
)
I want to have an array like this:
Array
(
[Q1] => 100
[Q2] => 200
[Q3] => 300
)
So basically I want to split all arrays in one, and 0 key of all multi arrays will be key in the new array and 1 value in multi-array will be value in the new array. I tried with array_combine, but that does not work for me, any ideas?
There's a function for that:
$result = array_column($array, 1, 0);
Failing that just loop:
foreach($array as $v) { $result[$v[0]] = $v[1]; }
Use this straight-forward solution :
$arr = [
['Q1',100],
['Q2',200],
['Q3',300]
];
$res = array_combine(
array_column($arr, 0),
array_column($arr, 1)
);
print_r($res);

Removing subarrays that share a key-value pair with another multidimensional array

I have 2 arrays as below. I want to remove data from array2 if array1 has the stu_id. final array should be like result_array.
$array1 = Array
(
[0] => Array
(
[stu_id] => 1
[name] => mr.a
)
[1] => Array
(
[stu_id] => 3
[name] => mr.b
)
)
$array2 = Array
(
[0] => Array
(
[id] => 1
[stu_id] => 1
[data] => abc
)
[1] => Array
(
[id] => 2
[stu_id] => 2
[data] => xyz
)
[3] => Array
(
[id] => 3
[stu_id] => 3
[data] => aaa
)
)
$result_array = Array
(
[0] => Array
(
[id] => 2
[stu_id] => 2
[data] => xyz
)
)
I tried array_diff, $result_array = array_diff($array2, $array1); but it's not working.
Please help me to do this.
Temporarily assign keys using array_column() with stud_id (NULL retains the full subarray data), then use array_diff_key() to filter, and array_values() to reset the keys:
Code: (Demo)
$array1=[
['stu_id'=>1,'name'=>'mr.a'],
['stu_id'=>3,'name'=>'mr.b']
];
$array2=[
['id'=>1,'stu_id'=>1,'data'=>'abc'],
['id'=>2,'stu_id'=>2,'data'=>'xyz'],
['id'=>3,'stu_id'=>3,'data'=>'aaa']
];
//var_export(array_column($array1,NULL,'stu_id'));
//var_export(array_column($array2,NULL,'stu_id'));
var_export(array_values(array_diff_key(array_column($array2,NULL,'stu_id'),array_column($array1,NULL,'stu_id'))));
Output:
array (
0 =>
array (
'id' => 2,
'stu_id' => 2,
'data' => 'xyz',
),
)
If you'd like to use a foreach loop structure, generate a filtering array of stu_id's from $array1 and write a conditional check on each iteration of $array2. This method doesn't not modify the original arrays, so they can be reused "down script".
Code:
$stu_ids=array_column($array1,'stu_id');
foreach($array2 as $row){
if(!in_array($row['stu_id'],$stu_ids)){
$result[]=$row; // auto-index the qualifying subarrays
}
}
var_export($result);
// same result as above method
foreach($array1 as $data1){
foreach($array2 as $k => $data2){
if($data2["stu_id"] == $data1["stu_id"]){
unset($array2[$k]);
break;
}
}
}
$result_array = $array2;

Return the difference of multi-dimensional arrays

how can I compare these two arrays?
I want the result be elements that are not available in one array. For example:
Array #1
Array
(
[0] => Array
(
[0] => a
[1] => 1
)
[1] => Array
(
[0] => b
[1] => 2
)
[2] => Array
(
[0] => c
[1] => 3
)
)
Array #2
Array
(
[0] => Array
(
[0] => a
[1] => 1
)
[1] => Array
(
[0] => b
[1] => 2
)
)
Result
Array
(
[0] => Array
(
[0] => c
[1] => 3
)
)
In set theory this is call symmetrical difference.
First you need to remove any possible duplicates, then get the individual differences for both arrays and the merge those two individual differences.
$a = array('John', 'Bob', 'Mary', 'Serena');
$b = array('Jim', 'Mary', 'John', 'Bob');
// Remove any duplicates
$a = array_unique($a);
$b = array_unique($b);
// Get the individual differences, using array_diff()
$a_minus_b = array_diff($a, $b);
$b_minus_a = array_diff($b, $a);
// Simply merge them together to get the symmetric difference
$symmetric_difference = array_merge($a_minus_b, $b_minus_a); // produces ['Serena', 'Jim']
You may need to make the necessary changes for a 2D array if you need to.
I hope this help.

Merge two multidimensional arrays, preserve numeric keys, and combine values inside array

I have two arrays and would like to combine / merge / put them together.
$arr1 = array(
0 => array(1, 2),
1 => array(5, 6)
);
$arr2 = array(
0 => array(2, 3),
1 => array(6, 7)
);
come_together_right_now($arr1, $arr2); // the missing function?
and the result would be:
Array (
[0] => Array (
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array (
[0] => 5
[1] => 6
[2] => 7
)
There are way too many array functions! array_merge and array_combine and the recursive alternatives seem to replace the values and they don't preserve numeric keys. How do I do this?
Assuming that they will always have the same keys!
$result = array();
foreach($arr1 as $key=>$array) {
$result[$key] = array_merge($array, $arr2[$key]);
}
I might be late of answering this question but this might help you simply using array_map,array_merge and array_unique function like as
$result = array_map('array_unique',array_map('array_merge',$arr1,$arr2));
print_r($result);
Output
Array (
[0] => Array (
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array (
[0] => 5
[1] => 6
[2] => 7
)
Demo
Synchronously iterate the arrays to access their rows.
Merge rows, remove duplicates, then re-index the elements.
Code: (Demo)
var_export(
array_map(
fn(...$rows) => array_values(array_unique(array_merge(...$rows))),
$arr1,
$arr2
)
);

Need common arrays from two multidimensional arrays

Hi I have below multidimensional arrays -
Array
(
[user_attempts] => 0
[2] => Array
(
[0] => 1
[1] => 4
)
[3] => Array
(
[0] => 32
[1] => 23
)
[4] => Array
(
[0] => asdsa
)
[1] => Array
(
[0] => Earth
)
)
and my second array is like below
Array
(
[1] => Array
(
[0] => Earth
)
[2] => Array
(
[0] => 2
[1] => 3
)
[3] => Array
(
[0] => 32
[1] => 23
)
[4] => Array
(
[0] => asdsa
[1] => asdas
)
)
I need to intersect both multidimensional arrays - so the result would be
Array
(
[1] => Array
(
[0] => Earth
)
[3] => Array
(
[0] => 32
[1] => 23
)
)
Can anyone help me to sort this out.
What I have tried is using array_intersect() but it limits to single array not multidimensional i guess.
PHP comes with a ton of functions already built in, but sometimes you still have to implement things yourself. What you want to do can be easily done by using the existing functions.
The goal is to do the following steps:
Find the keys that exist in both arrays
Loop through the array using these keys
Take the items of both input arrays with each of these keys
Calculate the intersection of those two arrays
Put it into a result array
Here is one way to do this:
function array_intersect_2dim (array $a1, array $a2) {
$keys = array_intersect(array_keys($a1), array_keys($a2));
$return = array();
foreach ($keys as $key) {
$return[$key] = array_intersect($a1[$key], $a2[$key]);
if (sizeof($return[$key]) == 0) {
unset($return[$key]);
}
}
return $return;
}
It works only for two dimensions. If you need more, you have to build a recursive approach, which follows the exact same principle.
To make the easier to compare you can use serialize/unserialize on this one. And then use array_intersect(). Try this example: Sample Output
$array1 = array( 'user_attemps' => 0, 2 => array(1, 4), 3 => array(32, 23), 4 => array('asdsa'), 1 => array('Earth'),);
$array2 = array( 1 => array('Earth'), 2 => array(2, 3), 3 => array(32, 23), 4 => array('asdsa', 'asdas'),);
$result = array_map('unserialize',array_intersect(array_map('serialize', $array1), array_map('serialize', $array2)));
print_r($result);

Categories