1

ラベルを作成するために、MySQL データベースから次のデータを抽出しました。

壊す

名前:RAJ
会社:ABC
注文番号:101

注文詳細:
アイテム1
アイテム20
アイテム3

壊す

名前:RAJ
会社:ABC
注文番号:101

注文詳細:
2×アイテム1
2×アイテム2
2×アイテム3

壊す

名前:RAJ
会社:ABC
注文番号:101

注文詳細:
5×アイテム4
5×アイテム5
5×アイテム2

PHPでBREAKの位置を見つけるコードを書いたところ、以下のような行番号を生成できます。

2
14
26
36

2行目から14行目まで、26行目から36行目までを1ファイルにまとめたファイルが欲しいです。私はphpで作業していて、shell_exec関数からsedを使用しようとしましたが、この出力を読んでsedコマンドを生成すると、最初の2つの数字が一緒になりません。

私が期待しているのは以下です。

sed -n 2,14p file1.txt
sed -n 26,36p file2.txt

PHPまたはシェルスクリプトで何か提案はありますか?

4

1 に答える 1

0

配列内の範囲を取得するには、array_slice()を使用します。私のソリューションは、要件に非常に固く結び付けられています。つまり、最初の行はすべて開始範囲番号であり、終了範囲に続きます。

// the lines from which will be read
$lines = "1
5
16
26";
// split these numbers above into an array
$lines = explode(PHP_EOL, $lines);

// the source file where the ranges will be taken off
$file = file('file.txt');


for($i = 0; $i < count($lines); $i+=2) {
  $rangeStart  = $lines[$i];
  $rangeLength = $lines[$i+1] - $lines[$i];

  // slice out the ranges, beware the second parameter is the length not the offset!
  $ranges[] = array_slice($file, $rangeStart, $rangeLength);

}

print_r($ranges);

ただし、可能であれば、ソース ファイル/テキスト/文字列 (?) で直接自動的に実行する方がはるかに簡単です。

$file = file('file.txt');
$len  = count($file);

$output  = array();
$current = array();
for($i = 0; $i < $len; $i++) {
  $data = trim($file[$i]);

  if ($data != 'BREAK') {
    $current[] = $data;
  } else {
    $output[] = implode(PHP_EOL, $current);
    $current  = array();
  }
}

print_r($output);
于 2012-04-25T19:28:54.157 に答える