开发者

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

I.e. 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/>';
    }
?&开发者_开发技巧gt;


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";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜