2012-04-25 4 views
1

다음 데이터가 MySQL 데이터베이스에서 추출되어 레이블을 만들었습니다.인쇄 할 줄 번호를 기반으로 파일 만들기

 

BREAK 

Name:RAJ 
Company:ABC 
Order Number:101 

Order Details: 
Item1 
Item20 
Item3 

BREAK 

Name:RAJ 
Company:ABC 
Order Number:101 

Order Details: 
2 x Item1 
2 x Item2 
2 x Item3 

BREAK 

Name:RAJ 
Company:ABC 
Order Number:101 

Order Details: 
5 x Item4 
5 x Item5 
5 x Item2 

나는 PHP에서 BREAK의 위치를 ​​찾기 위해 몇 가지 코드를 작성했으며 아래에 행 번호를 생성 할 수 있습니다.

 
2 
14 
26 
36 

나는 하나 개의 파일에 36 라인이 하나 개의 파일에 14과 26 사이에있는 내용의 파일을 원한다. 나는 PHP에서 일하고 shell_exec 함수에서 sed를 사용해 보았습니다. 그러나이 출력을 읽고 sed 명령을 생성하면 처음 2 개의 숫자가 함께 나오지 않습니다.

내가 기대하는 바는 아래와 같습니다.

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

PHP 또는 셸 스크립트에서 제안 사항이 있습니까?

+0

나는 앞서 가서 당신이 * 크레이 팅 * 파일을 만들지 않았다고 생각했습니다. :) – Christian

답변

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); 
관련 문제