为了账号安全,请及时绑定邮箱和手机立即绑定

如何合并由 php 中的 foreach 循环生成的 2 个数组

如何合并由 php 中的 foreach 循环生成的 2 个数组

PHP
拉风的咖菲猫 2023-03-04 16:12:14
大概是这样的情况:我有很多txt文件和一个1行,有tags存储的,有的是单独的,有的是逗号分隔的。所以一个 txt 文件看起来像这样:...aaa,bbb,ccc // tag line; 3 tags...或者...aaa,ccc // tag line; 2 tags...或者...bbb // tag line;single tag...我想要实现的目标:读取每个 txt 文件中的所有标记行并将标记放入一个数组中。同名标签在数组中应该只出现一次 (array_unique)到目前为止我所拥有的:$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 arrayforeach($tag_lines as $tag_line) {    echo $tag_line;}假设每行中只有 1 个标签,这工作正常。假设我有 3 个 txt 文件。当某些行有多个标记时,逗号分隔,我的输出如下所示:aaa,bbb,cccaaa,cccbbb输出应该是这样的:aaa bbbccc我试过这个: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;}不幸的是,我仍然得到这样的输出:aaa,bbb,cccaaa,cccbbb
查看完整描述

2 回答

?
繁华开满天机

TA贡献1816条经验 获得超4个赞

对于每个文件:读取它,检索第 7 行,用逗号分隔该行,对于该行中的每个字符串,将其添加到唯一键数组中,使用该字符串作为数组键。


$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;

  }

}

那时,$unique_tags将包含所有唯一键(作为键和值)。


查看完整回答
反对 回复 2023-03-04
?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

根据上面的答案,另一种选择是使用array_count_values。在这种情况下,数组的所有键都是唯一的,但它还会计算数组中出现的键数:


$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 />'; 

}

您的输出将类似于:


aaa(2) // 2 keys found with aaa

bbb(2) // 2 keys found with bbb

ccc(2) // 2 keys found with ccc


查看完整回答
反对 回复 2023-03-04
  • 2 回答
  • 0 关注
  • 147 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信