简体   繁体   English

PHP获得独特的参数

[英]PHP get unique params

I have this text file: 我有这个文本文件:

1 - word
1 - trata
2 - love
2 - green
2 - omg
3 - hello

How to parse this file so that I get the following? 如何解析此文件,以便获得以下信息?

1 - word, 1 - trata
2 - love, 2 - green, 2 - omg
3 - hello

Ie the same numbers on the same line. 即同一行上的相同数字。

<?php
    $file = file('1.txt');

    foreach ($file as $dd)
    {
        list ($numb, $word) = explode(' - ', $dd); // That's all (
        //echo $numb . '<br/>';
    }
?>

Something like this (untested): 像这样(未经测试):

$file = file('1.txt');
$parse = array();

foreach ($file as $dd)
{
    list ($numb, $word) = explode(' - ', $dd);
    $parse[ $numb ][] = $dd;
}

foreach( $parse as $line ) {
    echo implode( ', ', $line ).'<br />';
}
sort($file);
foreach ($file as $dd)
{
   list ($numb, $word) = explode(' - ', $dd); // That's all (
   if ($previous != $numb && $previous != null)
   {
       echo "<br>";
   }
   echo $numb ."-".$word ;       
   $previous=$numb;
}
$lines = file('test.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$map = array(); // Keys will be your "prefix numbers", values will be the lines from the file.

foreach($lines as $line)
{
    if(!preg_match('/^(\d+)/', $line, $match))
        continue;

    $map[$match[1]][] = $line;
}

// Now echo the result.

foreach($map as $n => $lines)
{
    echo implode(', ', $lines), '<br />';
}

// That's all.
<?php
$file = file('1.txt');
$output = array( );
foreach( $file as $line ) {
    list( $key, $value ) = explode( " - ", $line );
    $output[ $key ][ ] = trim( $value );
}
foreach( $output as $key => $values ) {
    foreach( $values as $value ) {
        echo $key . " - " . $value . ", ";
    }
    echo "\n";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM