2014-05-14 4 views
1

저는이 서클에서 돌아 다니며 누군가가 도울 수 있기를 바라고 있습니다.PHP를 사용하여 CSV 매트릭스에서 특정 값을 선택하십시오.

내가 예 데이터를 포함하는 .csv 파일을 가지고

중량 10, 20, 30, 40

제품 1, 1, 2, 3, 4

제품 2, 2 , 4, 6, 8

제품 3, 3, 6, 9, 12

내가해야 할 일은

, PHP를 사용하는 행이 "product2"이고 해당 행의 숫자가 27의 가중치와 가장 가까운 둥근 일치에 해당하는 값을 선택합니다. 따라서 결과는 6이어야합니다.

fgetcsv를 사용하여 배열에 csv 행을 추가하고 첫 번째 배열 item = product2가있는 행을 가져 오는 루프를 반복하지만 1 행의 Weight 값을 참조 할 수는 없습니다.

이 CSV가 효과적입니다. 거꾸로하지만 이것을 관리하는 가장 쉬운 방법입니다.

나는 도움이된다면 약간의 코드를 게시 할 수 있지만 솔직히 말해서 누군가가 제대로 작동하는 코드를 사용하여 나를 가리킬 수 있기를 바랄 뿐이다.

도움을 주시면 감사하겠습니다. 감사.

답변

-1

가장 가까운 둥근 성냥이 무엇인지 정의해야합니다. 24의 경우 20의 값을보아야합니까? 나는 당신이 24를 위해 그것을 위해 무엇을 사용 하는지를 이해함에 따라 30을 가져야한다고 생각한다. 그렇지 않으면 가중치의 절반 (첫 번째 열)에 대해 정의되어야 하는지를 정의해야한다.

나는 그것이해야한다고 생각으로는 (I 더 공간이 일반 CS 파일로, 이후이없는 가정) 30

PHP file: 


<?php 

$name = 'product2'; 
$weight = 24; 

$lines = explode("\n", file_get_contents("test.csv")); 

$found= ''; 

$foundCost = false; 

foreach ($lines as $line) { 
    if (strpos($line,$name.',') === 0) { 
    $found = $line; 
    break; 
    } 
} 






if ($found != '') { 
    $found = explode(',', $found); 
    $weights = explode(',',$lines[0]); 

    $index = false; 

    for ($i=1; $i<count($weights); ++$i) { 
     if ($weights[$i] >= $weight) { 
      $index = $i; 
      break; 
     }  
    } 
    if ($index !== false) { 
     $foundCost = $found[$index];  
    } 

} 

if ($foundCost !== false) { 

    echo "found ".$foundCost; 
} 

CSV 파일을 선택합니다 (24), 그래서 작동 샘플 코드가있다 :

Weight,10,20,30,40 
product1,1,2,3,4 
product2,2,4,6,8 
product3,3,6,9,12 
+0

대단히 고마워! 그것은 내가 필요한 것입니다. 귀하의 빠른 응답은 대단히 감사합니다! – washoc

0
<?php 
    $first_line; 
    $other_lines_separated; 
    $file=file('CSV_File_location'); //Put file contents in an array with each item being a line 
    foreach($file as $f){ 
     //Get each line then break that line an into a array 
     $values=explode(',',$f); 
     //If this is the first line we want it separate 
     if($f== $file[0]){ 
      $first_line=$values; 
     }else{ 
      $other_lines_separated[]=$values; 
     } 
    } 


//We now have an array with the first line and an array holding the other arrays with values separated 
//Go through each of the other arrays and do what you need 

for($i=0;$i<count($other_lines_separated); $i++){ 
     $other_line= $other_lines_separated[$i]; 
     for($y=0;$y<count($other_line); $y++){ 
     // in here we'll have access to any value we need 
     if($other_line[$y] == "product1"){ 
      //We're on the product1 line 
     } 
     if($other_line[$y] == "product2"){ 
      //We're on the product2 line 
     } 
     if($other_line[$y] == "product3"){ 
      //We're on the product3 line 
     } 
     echo "currently at value ".$other_line[$y]."</br>"; 
     } 
} 




?> 
+0

답장을 보내 주셔서 감사합니다. 코드는 csv를 통해 멋지게 반복되지만 @Marcin이 게시 한 코드는 내가 필요한 것을 정확히 수행하므로 대답으로 선택했습니다. 귀하의 답변은 비록 감사하겠습니다. – washoc

관련 문제