Search code examples
phparraystext-filesunique

PHP Convert Text File to Array and Merge with another Array


I have a main.txt file that contains the following:

new featuredProduct('', '25844'), 
new featuredProduct('', '19800'), 
new featuredProduct('', '23869'), 
new featuredProduct('', '23903'), 
new featuredProduct('', '14573'), 
new featuredProduct('', '7949'), 
new featuredProduct('', '13815'), 
new featuredProduct('', '27042'), 
new featuredProduct('', '24383'),

I also have trim.txt file that contains the following:

14573
23903
19800

I am attempting to convert trim into the same format as main, combine both as one array, then filter out the duplicates with array_unique.

What I've Tried:

$main = array_unique(file("main.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
$trim = array_unique(file("trim.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));

//formats trim to the same as main

foreach ($trim as $m) {
    $m = "new featuredProduct('', ". "'". urlencode(trim($m)) ."')" . "," . "\n<br />";
    echo $m;
}

//merge into one array
$t = (array) $m;
$res = array_unique(array_merge($t, $main));

foreach ($res as $re) {
echo $re . "<br>";
}

My Result:

I am getting the following output:

new featuredProduct('', '25844'), 
new featuredProduct('', '23903'), 
new featuredProduct('', '19800'), 

new featuredProduct('', '25844'), 
new featuredProduct('', '19800'), 
new featuredProduct('', '23869'), 
new featuredProduct('', '23903'), 
new featuredProduct('', '14573'), 
new featuredProduct('', '7949'), 
new featuredProduct('', '13815'), 
new featuredProduct('', '27042'), 
new featuredProduct('', '24383'),

So as you can see both arrays are getting displayed but they are not merging and displaying the unique values.

I think what's going wrong is that as soon as I loop over $trim and assign to $m, it's no longer an array. I have tried to assign $m to an array $t ..

$t = (array) $m;

then passed $t to the array_merge function, but this is not working.

So my question is how can I make $m an array that works and can be passed to the array_merge() therefore allowing me to display just unique values in the merged array?

Cheers


Solution

  • Several issues, among them: Don't add \n<br /> to $trim that makes it different and not unique. Also, $m will only be the last one in the loop.

    Make sure to use the & for $m in the loop to change the actual array:

    $main = file("main.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $trim = file("trim.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    
    foreach ($trim as &$m) {
        $m = "new featuredProduct('', '" . urlencode(trim($m)) . "'),";
    }
    $res = array_unique(array_merge($trim, $main));