Reputation: 41
I have two CSV files called whatineed.csv / all.csv and I want to print out the data only when it exists in both the files.
I tried some functions but nothing seems to give me the output I need.
Thanks in Advance
whatineed.csv got:
Array
(
[0] => 0424
[1] => 9007382026
)
Array
(
[0] => 15043
[1] => 90073225
)
Array
(
[0] => 15043-3
[1] => 900735226
)
all.csv
Array
(
[0] => 0424
[1] => Text
[2] => Text
[3] => Text
[4] => Text
[5] => 9007382026
)
Array
(
[0] => 456456
[1] => Text
[2] => Text
[3] => Text
[4] => Text
[5] => 486424
)
Array
(
[0] => 15043-3
[1] => Text
[2] => Text
[3] => Text
[4] => Text
[5] => 900735226
)
I tried to use in_array
$sourceall = all.csv;
$sourceneed = whatineed.csv;
if (($handle1 = fopen($sourceall, "r")) !== FALSE && ($handle = fopen($sourceneed, "r")) !== FALSE) {
while (($data1 = fgetcsv($handle1, 0, "|")) !== FALSE && ($data = fgetcsv($handle, 0, "|")) !== FALSE) {
if (in_array($data[$mainInfo[2]], array_column($data1, $data1[$mainInfo1[5]]))) {
print_r($data1);
}
// another one
if(in_array($data[$mainInfo[0]], $data1)){
print_r($data1);
}
}
}
This is what I want to print out
Array
(
[0] => 0424
[1] => Text
[2] => Text
[3] => Text
[4] => Text
[5] => 9007382026
)
Array
(
[0] => 15043-3
[1] => Text
[2] => Text
[3] => Text
[4] => Text
[5] => 900735226
)
because the array elements from whatineed.csv exists in all.csv
Upvotes: 0
Views: 59
Reputation: 18557
You can use some combinations of array_column and array_intersect_key as follows,
$temp = array_column($a1, null, 0); // considers 0 as key and null means whole array as value
$temp1 = array_column($a2, null, 0);
$temp2 = array_intersect_key($temp1, $temp); // array_intersection based on matching key
Create $a1
and $a2
from whatineed.csv
and all.csv
respectively. Then pass those two arrays to above snippet, it will work.
Upvotes: 1