如何在PHP中过滤文本块并将其排序为数组?

时间:2015-07-18 07:48:12

标签: php arrays

我有一个简单的文本块,包含3列:

id_1    text_1  A
id_9    text_2  B
id_2    text_5  D
id_3    text_3  G
id_8    text_4  C
id_4    text_9  X
id_0    text_0  X
id_5    text_8  Z
...

和PHP数组:

$std_string = array ("A", "B", "X", "C", "M");

我想根据$std_string中的顺序和现有文本,将文本块过滤并排序为新的文本块。

确切地说,它将返回一个新的文本块:

id_1
id_9
[DU]
id_8
[NO]

如果第3列(原始文本块)在第1列中没有值(在$std_string中列出)(如 M ),它将会返回 [NO]

如果第3列(原始文本块)在第1列中有两个值(如 X ),它将返回 [DU]

有什么建议可以在PHP中进行吗?

  

所有数据区分大小

1 个答案:

答案 0 :(得分:2)

这是:

$text_block="id_1    text_1  A
id_9    text_2  B
id_2    text_5  D
id_3    text_3  G
id_8    text_4  C
id_4    text_9  X
id_0    text_0  X
id_5    text_8  Z";

$std_string = array ("A", "B", "X", "C", "M");

$rows = explode("\n", str_replace("\r","",str_replace("\t"," ",$text_block)));

$letter_ids = array();
foreach($std_string as $letter) {
    $letter_ids[$letter] = "[NO]";
}
for($i=0;$i<count($rows);$i++) {
    $cols = explode(" ",trim($rows[$i]));
    $letter = $cols[count($cols)-1];
    if(isset($letter_ids[$letter])) {
        if($letter_ids[$letter] == "[NO]") {
            $letter_ids[$letter] = $cols[0];
        } else {
            $letter_ids[$letter] = "[DU]";
        }
    }
}

$new_text_block = "";
foreach($letter_ids as $key => $val) {
    $new_text_block.= $val."\n";
}
echo "<pre>".$new_text_block."</pre>";

输出:

id_1
id_9
[DU]
id_8
[NO]