如何添加到数组而不覆盖(从读取行和爆炸)PHP

问题描述:

I have the following code:

 while(! feof($file))
      {
    $n=$n+1;

    if($denetleme == 0){
     $detay[$n]= fgets($file);

    $detay[$n] = str_replace("
", "", $detay[$n]);
    $detay[$n] = str_replace("", "", $detay[$n]);

    if (empty($detay[$n])) {
    $denetleme=1;
    }
     }elseif($denetleme == 1) {

            $x=$x+1;
            $hamle1[$x]= fgets($file);
            $hamle1[$x] = str_replace("
", "", $hamle1[$x]);
            $hamle1[$x] = str_replace("", "", $hamle1[$x]);

            if (empty($hamle1[$x])) {
            break;
                                    }

            $hamle = explode(" ", $hamle1[$x]);         .........

Now the final line works but each time 'while(! feof($file))' repeats, it overwrites $hamle (which is an array). How can I add to $hamle until the process is finished without overwriting?

The output is something like this=>

Array ( [0] => 1.e4 [1] => c5 [2] => 2.Nf3 [3] => Nc6 [4] => 3.d4 [5] => cxd4 [6] => 4.Nxd4 [7] => Nf6 [8] => 5.Nc3 [9] => e5 [10] => )
6.Ndb5 d6 7.Bg5 a6 8.Na3 b5 9.Bxf6 gxf6 10.Nd5 f5 This is hamle

Array ( [0] => 6.Ndb5 [1] => d6 [2] => 7.Bg5 [3] => a6 [4] => 8.Na3 [5] => b5 [6] => 9.Bxf6 [7] => gxf6 [8] => 10.Nd5 [9] => f5 [10] => )
11.Bd3 Be6 12.O-O Bxd5 13.exd5 Ne7 14.Nxb5 Bg7 15.Nc3 e4 This is hamle 

I need the whole thing added to each other as a single array... Thank you all...

The file I am reading is =>

[Event "MT-Bielecki/Top (POL)"]
[Site "ICCF"]
[Date "2012.3.1"]
[Round "-"]
[White "Langeveld, Ron A. H."]
[Black "Starke, Dr. René-Reiner"]
[Result "1/2-1/2"]
[WhiteElo "2681"]
[BlackElo "2620"]

1.e4 c5 2.Nf3 Nc6 3.d4 cxd4 4.Nxd4 Nf6 5.Nc3 e5 
6.Ndb5 d6 7.Bg5 a6 8.Na3 b5 9.Bxf6 gxf6 10.Nd5 f5 
11.Bd3 Be6 12.O-O Bxd5 13.exd5 Ne7 14.Nxb5 Bg7 15.Nc3 e4 
16.Bc4 Ng6 17.Qh5 Bxc3 18.bxc3 Qf6 19.Qh6 Qxc3 20.Be2 Qe5 
21.g3 Ke7 22.Rae1 Rac8 23.c4 f4 24.Bd3 f5 25.Be2 Rb8 
26.Kh1 Kd8 27.gxf4 Nxf4 28.c5 dxc5 29.Qc6 Rc8 30.Qb6+ Ke7 
31.f3 Nxd5 32.Qxa6 Rcd8 33.Bc4 Nc7 34.Qh6 Rd4 35.Bb3 Rf8 
36.fxe4 Rxe4 37.Rb1 Nd5 38.Bc2 Re8 39.Rfd1 Rb4 40.Qxh7+ Kd6 
41.Rxb4 cxb4 42.Bxf5 Re7 43.Qh3 Qe1+ 44.Rxe1 Rxe1+ 45.Kg2 Nf4+ 
46.Kf2 Nxh3+ 47.Kxe1 1/2-1/2

You're reset the value $hamle each time you loop through your code, you need to push a new element into the array. If you don't need to push a sub array into $hamle, $hamle1 doesn't need to be an array.

Try:

Before while loop:

$hamle = array( );

Inside loop:

$hamle1= fgets($file);
$hamle1 = str_replace("
", "", $hamle1);
$hamle1 = str_replace("", "", $hamle1);
$hamle1 = explode(" ", $hamle1);

and to add to $hamle:

foreach($hamle1 as $item)
{
    $hamle[] = $item;
}

or

foreach($hamle1 as $item)
{
    array_push($hamle, $item)
}