2012-03-13 2 views
3

EDIT: Хорошо, я немного ближе, но все еще нужна помощь ... http://pastebin.com/9vdhGT2VГруппировка команды вместе после обработки - НЕ ДЛЯ КОММЕРЧЕСКОГО ИСПОЛЬЗОВАНИЯ

Отказ от ответственности: Это мой первый пост после использования SO как ресурс долгое время , Я не ленив, я просто исчерпал поиск, и я близок. Мне просто нужно толкнуть некоторых дружелюбных более опытных кодеров. Заранее спасибо!

Я использую Простую HTML DOM, чтобы закончить Yahoo Sports и получить оценки. У меня возникают проблемы с группировкой двух команд, которые играют вместе в таблице. Я знаю, что мне нужно будет засчитать на 2, так как это очень предсказуемо. У меня просто возникают проблемы с его правильной настройкой.

Это последний кусок рабочего кода у меня есть, но это не группа по командам играть друг с другом:

http://pastebin.com/0LzrV0Ej

<?php 

require('simple_html_dom.php'); 
$nbaScores = "http://sports.yahoo.com/nba/scoreboard"; 
$html = file_get_html($nbaScores); 

// Find all game info 
foreach($html->find('tr.ysptblclbg5') as $scores){ 
    echo "<table><tr><td>".$scores->find('td',0)->plaintext. "</td>"; 
    echo "<td>".$scores->find('td',1)->plaintext. "</td>"; 
    echo "<td>".$scores->find('td',2)->plaintext. "</td>"; 
    echo "<td>".$scores->find('td',3)->plaintext. "</td>"; 
    echo "<td>".$scores->find('td',4)->plaintext. "</td>"; 
    echo "<td>".$scores->find('td',5)->plaintext. "</td>"; 
    echo "<td>".$scores->find('td',6)->plaintext. "</td>"; 
    echo "<td>".$scores->find('td',7)->plaintext. "</td></tr></table>"; 
    } 

unset($scores); 

?> 

Ура!

+2

Yahoo не позволяет просто захватить их страницы, это незаконно – zerkms

+0

Это не для коммерческого использования. – Brent

+4

@zerkms Его проблема, а не наша; и я не считаю, что это может быть признано незаконным для скрининга сайта, его можно считать фактически незаконным для использования указанных данных способами, которые его лицензия не позволяет. – Ben

ответ

1

Редактировать: код теперь будет отображать опциональную TD. Я предполагаю, что $ parse-> find ("tag [атрибут = значение]") возвращает таблицу объектов, которые реализуют -> plaintext.

Редактировать # 2: код теперь будет знать, какая команда выиграла матч (используя подтаблицу из $ команд).

Edit # 3: на основе комментариев: исправлена ​​скобка, исправила команду сдвига в таблице от редактирования # 1

Никогда не использовал этот парсер, поэтому предполагаются, что ваши методы синтаксического анализа работы (и предполагая, я Жду» т запутаться в индексах TD), но в любом случае здесь логика:

$periods=array("QT1","QT2","QT3","QT4","OT","Total"); 
$scores=array(); 
$teams=array(); 
$teamCount=0; 
$matchesCount=0; 
foreach($html->find('tr.ysptblclbg5') as $parse){ 
    $teams[$matchesCount][$teamCount]['name']=$parse->find('td',1)->plaintext; //TD#2 contains the team name 
    //TDs 3 to 6 contain partial scores, TD#7 contains final score or OT score (in which case TD#8 contains final score), they all have the "yspscores" class 
    $pscores=$parse->find('td[class=yspscores]'); 
    for($i=1;$i<count($pscores);$i++) { //we start at 1 instead of 0 as the first TD grabbed is the one where the team name is written, as it also has the yspscores class 
     if($i==count($pscores)-1) //if we are at the total score 
      $scores[$matchesCount][$teamCount][$periods[count($periods)-1]]=$pscores[$i]->plaintext; 
     $scores[$matchesCount][$teamCount][$periods[$i-1]]=$pscores[$i]->plaintext;//$periods[$i-1] as $periods doesn't have a useless offset like $pscores has (part of edit#3) 
    } 
    $teamCount++; //finished a team and its scores, getting ready to move to the next 
    if($teamCount%2==0) { //true if we just parsed the 2nd team of a match 
     if($maxMatchScore>$scores[$matchesCount][1][$periods[count($periods)-1]]) //if 1st team won 
      $teams[$matchesCount][0]['win']=1; 
     else 
      $teams[$matchesCount][1]['win']=1; 
     $teamCount=0; //then reset the counter as next team will the first team parsed of next match 
     $matchesCount++; //and ready to move to next match 
    } else { 
     $maxMatchScore=$scores[$matchesCount][0][$periods[count($periods)-1]]; //if in the middle of parsing the match, memorize the total score of the first team, to know later who won 
    } 
} 

Там у вас есть 2 таблицы с командами и оценками разбираемых соответственно каждый матч. Теперь вы можете напечатать их так, как вы хотите:

foreach($teams as $match=>$subarray) { //teams and scores have their indexes coherent, we could have used scores instead, though subarray would have contained the scores instead of the teams (obviously ^^) 
    echo "<br /><br />Match #".($match+1).":<br />"; //prints the index of the match in the tables, +1 because "match number zero" is not NBA-friendly... 
    foreach($subarray as $id=>$team) { //if we had used scores instead of teams in the global loop, we would have had subarray as id => scoreArray 
     if(empty($team['win'])) { //the winner is bold 
      $b1=""; 
      $b2=""; 
     } else { 
      $b1="<b>"; 
      $b2="</b>"; 
     } 
     echo "Team: ".$b1.$team['name'].$b2.":"; //here team will print with the hyperlink, use a regexp to remove it if needed 
     //the following is still valid, but if you need to display a table, you'll have one more TD on matches with OT, which won't look nice 
     //foreach($scores[$match][$id] as $scoreType=>$score) { //the table selects one team of one match, and the corresponding subarray gives as keys the type of score (which quarter time, or final score), and as values the score for the paired index. 
      //echo $scoreType.":".$score; //prints "qt1:24", or "final:90" 
      //echo $scoreType=='final'?'<br />':'/'; //if it is a quarter's score, we separate the next score with a slash, while if it's the final score we <br> (either for the next team or for the next match, as we surely leave this loop, and maybe the previous ine if it was the 2bd team's scores) 
     //} 
     //version OK for table display or anything else 
     foreach($periods as $scoreType) { 
      echo $scoreType.":".(empty($scores[$match][$id][$scoreType])?"-":$scores[$match][$id][$scoreType]); //if no OT, we just print "-" where there could have been the OT 
      echo $scoreType==$periods[count($periods)-1]?'<br />':'/'; 
     } 
    } 
} 

Я не проверял этот код, так что могут быть некоторые опечаток, но цель для вас, чтобы иметь намек на то, как разобрать вещи в таблицах , что будет легче, если вы хотите, чтобы сосредоточиться на дисплее;)

Однако ... у меня нет юридической консультации для вас, извините ^^

+0

Довольно эпическое решение. Мне нужно немного переварить его. – Brent

+0

Большое спасибо. Мне нужно будет добавить несколько TD для возможных игр OT, но это место.(галочка) :) – Brent

+0

Это будет работать, мне просто нужно выяснить, как приспособить его к рассмотрению игр OT (дополнительные кварталы, поскольку они генерируют больше TD для этого), а затем как сбрасывать их в таблицы по совпадениям – Brent

Смежные вопросы