亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何合并由 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 關注
  • 221 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號