how to merge 2 arrays generated by a foreach loop in php

Viewed 48

It is about this situation: I have a lot of txt files and one 1 line, there are tags stored, some alone, some comma seperated. So an txt file looks like this:

...
aaa,bbb,ccc // tag line; 3 tags
...

or

...
aaa,ccc // tag line; 2 tags
...

or

...
bbb // tag line;single tag
...

What i want to achieve: read all the tag lines in each txt file and put the tags in an array. Tags with the same name should occure only once in the array (array_unique)

What i have so far:

$files = glob("data/articles/*.txt"); 
$tag_lines = array();
$lines = file($file, FILE_IGNORE_NEW_LINES);
$tag_lines[] =  $lines[7]; // 7th line is the tag line. Put all the tags in an array

foreach($tag_lines as $tag_line) {
    echo $tag_line;
}

Assuming when there is only 1 tag in each line, this works fine.

Lets say i have 3 txt files. When some lines have multiple tags, comma seperated, my output looks like this:

aaa,bbb,ccc
aaa,ccc
bbb

and the output should be like this :

aaa 
bbb
ccc

I tried this:

foreach($files as $file) { // Loop the files in the directory
   $lines = file($file, FILE_IGNORE_NEW_LINES);
   $single_tag_line = explode(',' , $lines[7]);
   $tag_lines[] =   $lines[7];
   $tag_lines = array_unique(array_merge($tag_lines , $single_tag_line));
}
foreach($tag_lines as $tag_line) {
    echo $tag_line;
}

Unfortunately, i still got an output like this:

aaa,bbb,ccc
aaa,ccc
bbb
2 Answers

For each file: read it, retrieve the 7th line, split that line on commas, and for each string in that line, add it to an array of unique keys, using the string as the array key.

$unique_tags = [];

foreach ( glob("data/articles/*.txt") as $file ) {
  $lines = file($file, FILE_IGNORE_NEW_LINES);
  $tags = explode( ',', $lines[7] ); // 7th line is the tag line. Put all the tags in an array

  // Process each tag:
  foreach ( $tags as $key ) {
    $unique_tags[ $key ] = $key;
  }
}

At that point, $unique_tags will contain all the unique keys (as both keys and values).

Another option, based on the answer above is to use array_count_values. In that case, you have all the keys of the array unique, but it calculates also the number of keys that occurs in the array:

$files = glob("data/articles/*.txt");                       
foreach($files as $file) { // Loop the files in the directory
    $lines = file($file, FILE_IGNORE_NEW_LINES);
    $tags = explode( ',', strtolower($lines[7]) ); // 7th line is the tag line. Put all the tags in an array

    // Process each tag:
    foreach ($tags as $key) {                                   
        $all_tags[] = $key; // array with all tags
        //$unique_tags[$key] = $key; // array with unique tags
    }
}
$count_tags = array_count_values($all_tags);
foreach($count_tags as $key => $val) {
    echo $key.'('.$val.')<br />'; 
}

Your output will be something like:

aaa(2) // 2 keys found with aaa
bbb(2) // 2 keys found with bbb
ccc(2) // 2 keys found with ccc
Related