How to do an intersection of arrays of arrays - php

I’m trying to do a function in php that try to make an intersection of an array of arrays. I have found array_intersect($resultx,$resulty); but it's working just for tables with one value. In my case I have arrays of arrays like that.
Array
(
[0] => Array
(
[name] => Chris
[id] => 1033
)
[1] => Array
(
[name] => Vins
[id] => 1034
)
[2] => Array
(
[name] => Steve
[id] => 1035
)
[3] => Array
(
[name] => Henry
[id] => 1036
)
[4] => Array
(
[name] => Jack
[id] => 1037
)
[5] => Array
(
[name] => Paul
[id] => 1038
)
)
To resume my problem I’m trying to make an intersection of lot of tables like the one i have mentioned. So any idea
examples tab1[[1,2,3],[2,3,1]] tab2[[1,2,3],[5,7,7] the result will be tab3[[1,2,3]] it is clear for you ?
Thanks

#KANDROID OS, Please check below example for intersection of arrays.
Suppose you have two array(s) like below:
$arr1 = array(
array('name' => 'Chris','id' => '1111'),
array('name' => 'Vins','id' => '1112'),
array('name' => 'Steve','id' => '1113'),
);
$arr2 = array(
array('name' => 'Chris','id' => '1111'),
array('name' => 'dddd','id' => '2222'),
);
You can use array_uintersect() to use a custom comparison function, like this:
$intersect = array_uintersect($arr1, $arr2, 'comparevalue');
print_r($intersect);
function comparevalue($val1, $val2)
{
return strcmp($val1['id'], $val2['id']);
}
So Outcome of above is like below :
Array
(
[0] => Array
(
[name] => Chris
[id] => 1111
)
)

You could recursively do it like this:
$arr1 = array(
array('name' => 'Chris', 'id' => '1033'),
array('name' => 'Vins', 'id' => '1034'),
array('name' => 'Steve', 'id' => '1035'),
array('name' => 'Henry', 'id' => '1036'),
array('name' => 'Jack', 'id' => '1037'),
);
$find = array( // Array for ANY search criteria,
array(1033), // name, id, etc.
array('Vins') // (Each element needs to be an array)
);
$match = array(); // Define array for results
for($i=0; $i < count($arr1); $i++){ // For every "name/id combo",
for($j = 0; $j < count($find); $j++){ // go through every search criteria
$thisMatch = array_intersect( $arr1[$i], $find[$j]); // and check for a match
if ($thisMatch){ // If a match was found,
$match[] = $arr1[$i]; // add it to the results array
}
}
}
var_dump($match);
This will result in:
Array
[0] =>
Array (
'name' => string 'Chris'
'id' => string '1033'
)
[1] =>
Array (
'name' => string 'Vins' (length=4)
'id' => string '1034' (length=4)
)
You have to be careful though, with the example using the callback, trying to use the intersect for 'name' AND 'id' values WILL NOT return paired values as you might expect. It only needs to find one of the values, so if you try to search for a 'name' that corresponds to a different 'id', you will get both items back, even if that "combination" doesn't exist. It will do the same thing even if you use the keys in the search like this:
$find = array(
array('id' => 1033),
array('name' => 'Vins')
);
I just noticed that issue so I thought I'd bring it up. Depending on what you're trying to do, you may need some sort of recursive aspect anyway, like I've shown.
Hope this helps :)

Related

How to move array in multidimensional array using key value?

How to move array in multidimensional aray with key value?
I'm using array_push to add values to a multidimensional array. i have an array
$myArray = Array(Array('code' => '1','room' => Array('name' => 'Room-A')),Array('code' =>'1','room' => Array('name' => 'Room-B'
)), Array('code' => '2','room' => Array('name' => 'Vip-1')),Array('code' => '2','room' => Array('name' => 'Vip-2')));
i tried using code like this:
for ($i=0; $i <count($myArray) ; $i++) {
if ($myArray[$i]['code']=='1') {
array_push($myArray[$i]['room'], $myArray[$i]['room']);
}
else{
array_push($myArray[$i]['room'], $myArray[$i]['room']);
}
}
i want the result like this :
Array
(
[0] => Array
(
[code] => 1
[room] => Array
(
[0] => Array
(
[name] => Room-A
)
[1] => Array
(
[name] => Room-B
)
)
)
[1] => Array
(
[code] => 2
[room] => Array
(
[0] => Array
(
[name] => Vip-1
)
[1] => Array
(
[name] => Vip-2
)
)
)
)
Any idea how to join this array?
You can use array_reduce to summarize the array into an associative array using the code as the key. Use array_values to convert the associative array into a simple array.
$myArray = ....
$result = array_values(array_reduce($myArray, function($c, $v){
if ( !isset( $c[ $v['code'] ] ) ) $c[ $v['code'] ] = array( 'code' => $v['code'], 'room' => array() );
$c[ $v['code'] ]['room'][] = $v['room'];
return $c;
},array()));
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to:
Array
(
[0] => Array
(
[code] => 1
[room] => Array
(
[0] => Array
(
[name] => Room-A
)
[1] => Array
(
[name] => Room-B
)
)
)
[1] => Array
(
[code] => 2
[room] => Array
(
[0] => Array
(
[name] => Vip-1
)
[1] => Array
(
[name] => Vip-2
)
)
)
)
This is the foreach() equivalent of Eddie's answer (I find it easier to read/maintain).
Code: (Demo)
$myArray = [
['code' => '1', 'room' => ['name' => 'Room-A']],
['code' => '1', 'room' => ['name' => 'Room-B']],
['code' => '2', 'room' => ['name' => 'Vip-1']],
['code' => '2', 'room' => ['name' => 'Vip-2']]
];
foreach ($myArray as $row) {
if (!isset($result[$row['code']])) {
$result[$row['code']] = ['code' => $row['code'], 'room' => [$row['room']]];
// ^------------^-- pushed deeper
} else {
$result[$row['code']]['room'][] = $row['room'];
// ^^-- pushed deeper
}
}
var_export(array_values($result));
This question is very similar to many pre-existing questions that want to group by a particular column. I was not able to find an exact duplicate to close with because the requirement of this question is to created a deeper structure to contain the room sub arrays.
Typically I would write:
if (!isset($result[$row['code']])) {
$result[$row['code']] = $row;
to cut down on syntax, but the new output structure must be applied to both the if and the else.
To avoid key duplication/collision, the room subarrays need to be pushed/indexed to a lower level.
In the end, the technique has been demonstrated here many, many times on StackOverflow. You target an element value to group by and use that value as the temporary key as you iterate the input array. Checking if the temporary keys exist or not is the fastest way to determine if a group is new or previously encountered. When you are done, call array_values() to remove the temporary keys (re-index the array).

Summarize the same key name in php multidimensional array

I have an array like this:
[0] => Array
(
[id_station] => 2397
[hour] => 12
[data] => Array
(
[cameraon] => 355654
[cameraoff] => 4532
[camerabroken] => 76745
...
)
)
[1] => Array
(
[id_station] => 2399
[hour] => 13
[data] => Array
(
[cameraon] => 3905466
[cameraoff] => 1672
[camerabroken] => 70780
...
)
)
I want to add one more row = total of all items
[1] => Array
(
[id_station] =>
[hour] =>
[data] => Array
(
[cameraon] => 4261120
[cameraoff] => 6204
[camerabroken] => 147525
)
)
I used array_sum(array_column($array["data], 'cameraon')) but I have to do for all items cameraon, cameraoff, camerabroken (I have a hundred items).
Is there any way to get total row in this case?
I assume that you don't know the depth of data sub-array. (that is how many key-value pairs are there)
So do like below:-
$final_array = [];
$final_array['id_station'] ='';
$final_array['hour'] ='';
foreach($original_array as $original_arr){
foreach($original_arr['data'] as $key=>$original){
$final_array['data'][$key] +=$original;
}
}
Output:-https://eval.in/926729
You wish to sum the columnar data, so leveraging array_sum() and array_column() are wise choices. The only thing left to do is set up the loop.
You can first isolate the data subarrays using array_column() then "drill down" into the first subarray to iterate each column. Use the column names to access all values in all columns. This makes the method dynamically successful regardless of the complexity of your data subarrays.
Code: (Demo)
$array=[
[
'id_station'=>2397,
'hour'=>12,
'data'=>['cameraon'=>355654,'cameraoff'=>4532,'camerabroken'=>76745]
],
[
'id_station'=>2399,
'hour'=>14,
'data'=>['cameraon'=>3905466,'cameraoff'=>1672,'camerabroken'=>70780]
]
];
$datas=array_column($array,'data'); // isolate the data subarrays
foreach(current($datas) as $column=>$data){ // iterate the columns
$result[$column]=array_sum(array_column($datas,$column)); // sum the column values
}
$array[]=['id_station'=>'','hour'=>'','data'=>$result]; // completenew item and append
var_export($array); // print to screen
Output:
array (
0 =>
array (
'id_station' => 2397,
'hour' => 12,
'data' =>
array (
'cameraon' => 355654,
'cameraoff' => 4532,
'camerabroken' => 76745,
),
),
1 =>
array (
'id_station' => 2399,
'hour' => 14,
'data' =>
array (
'cameraon' => 3905466,
'cameraoff' => 1672,
'camerabroken' => 70780,
),
),
2 =>
array (
'id_station' => '',
'hour' => '',
'data' =>
array (
'cameraon' => 4261120,
'cameraoff' => 6204,
'camerabroken' => 147525,
),
),
)

Move an element to first position in an array

here is my array:
Array
(
[0] => Array
(
[id] => 8
[title] => MUSIC
)
[1] => Array
(
[id] => 17
[title] => Indie
)
[2] => Array
(
[id] => 14
[title] => SPORTS
)
[3] => Array // Need to move this on first position
(
[id] => 15
[title] => Hipster
)
[4] => Array
(
[id] => 16
[title] => Web Seriesdf
)
)
I want array with key [3] to be on first position and then the rest of the elements.
I tried array_merge and array_unshift. But not working
You just need to take only three steps.
- Copy n'th array in variable.
- Delete n'th index from array. using unset()
- Put variable at the 0th index of the array. Using array_unshift()
Step 1:
$array=$mainArray[N];
Step 2:
unset($mainArray[N]);
Step 3:
array_unshift($mainArray, $array);
Lets assume your array to be $x;
$new_value = $x[3];
unset($x[3]);
array_unshift($x,$new_value);
This shall solve your problem.
You can also use array_merge
<?php
$a = [1,2,3,4,5];
$new_value = [$a[1]];
unset($a[1]);
$c = array_merge($new_value,$a);
print_r($c);
?>
Check output : https://eval.in/590702
Use
$array = array('3' => $array['3']) + $array;
phpfiddle Preview and eval.in Preview
Note: im moving 2 in my array. In your method add 3
Example
$array = array(
'0' => array(
'id'=>'8',
'title'=>'MUSIC'
),
'1' => array(
'id'=> '17',
'title'=> 'Indie'
),
'2' => array(
'id'=>'14',
'title'=>'SPORTS',
),
'3' => array(
'id'=>'14',
'title'=>'SPORTS',
),
);
$array = array('2' => $array['2']) + $array;
print_r($array);
Output
Array ( [2] => Array ( [id] => 14 [title] => SPORTS ) [0] => Array ( [id] => 8 [title] => MUSIC ) [1] => Array ( [id] => 17 [title] => Indie ) [3] => Array ( [id] => 14 [title] => SPORTS ) )
Use array_unshift();
Please check below code.
<?php
$a = Array(
'0' => Array('id' => '8','title' => 'MUSIC'),
'1' => Array('id' => '17','title' => 'Indie'),
'2' => Array('id' => '14','title' => 'SPORTS'),
'3' => Array('id' => '15','title' => 'Hipster'),
'4' => Array('id' => '16','title' => 'Web Seriesdf')
);
echo '<pre>';print_r($a);
$a3 = $a['3'];
unset($a['3']);
array_unshift($a,$a3);
echo '<pre>';print_r($a);
?>
Check output - https://eval.in/590723

php merge 2 arrays into one associative array

Using PHP I need to merge 2 arrays (of equal length into one associative array) here is an excerpt from my current data set:
[1] => Array
(
[0] => C28
[1] => C29
)
[2] => Array
(
[0] => 1AB010050093
[1] => 1AB008140029
)
both elements [1] and [2] are actually a lot longer than just 2 sub-elements (like I said, this is an excerpt).
The deal is that "C28" in the first array corresponds to "1AB010050093" in the second array, and so on... The result I need is to create a new associative array that looks like this:
[1] => Array
(
['ref'] => C28
['part'] => 1AB010050093
)
[2] => Array
(
['ref'] => C29
['part'] => 1AB008140029
)
and so on...
If you are willing to compromise with an array structure like this:
array(
'C28' => '1AB010050093',
'C29' => '1AB008140029'
);
Then you can use the array_combine() (Codepad Demo):
array_combine($refNumbers, $partIds);
Otherwise, you'll need to use a foreach (Codepad Demo):
$combined = array();
foreach($refNumbers as $index => $refNumber) {
if(!array_key_exists($index, $partIds)) {
throw OutOfBoundsException();
}
$combined[] = array(
'ref' => $refNumber,
'part' => $partIds[$index]
);
}
If you're using PHP 5.5+, there is a new method called array_column(), which will get all of the values in a particular column. That could potentially be used, although I think just a simple foreach loop will probably still be your best bet.
How about:
$arr1 = array(
0 => 'C28',
1 => 'C29',
);
$arr2 = array(
0 => '1AB010050093',
1 => '1AB008140029',
);
$result = array();
for ($i=0; $i<count($arr1); $i++) {
$result[] = array('ref' => $arr1[$i], 'part' => $arr2[$i]);
}
print_r($result);
ouptut:
[1] => Array
(
[0] => C28
[1] => C29
)
[2] => Array
(
[0] => 1AB010050093
[1] => 1AB008140029
)

smaller array based on array contents

I am looking for a way to create a new array based on array contents.
so i've got:
Array ( [0] => 1
[type] => first_value_i_need
[some_id] => 2
[hits] => 88
[some_other_id] => second_value_i_need
)
and i would like to get
Array ( [0] => 1
[app_name] => "first_value_i_need-second_value_i_need"
[hits] => "88"
)
I know that i need some sort of foreach function, but i'm right now lost.
No, you don't need any loops as long as you know which keys you need.
$old = array(
0 => 1,
'type' => 'first_value_i_need',
'some_id' => 2,
'hits' => 88,
'some_other_id' => 'second_value_i_need'
);
$new = array(
0 => $old[0],
'app_name' => $old['type'].'-'.$old['some_other_id'],
'hits' => $old['hits'],
);
So basically do you wnat to get rid of the app_table_id key ?
You can do unset($array['app_table_id']);
And if you need to change some value you can do :
$array['app_name'] = $array['some_other_id'];
//> Note i posted this before your edit.

Categories