Редактировать: код теперь будет отображать опциональную 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 />':'/';
}
}
}
Я не проверял этот код, так что могут быть некоторые опечаток, но цель для вас, чтобы иметь намек на то, как разобрать вещи в таблицах , что будет легче, если вы хотите, чтобы сосредоточиться на дисплее;)
Однако ... у меня нет юридической консультации для вас, извините ^^
Yahoo не позволяет просто захватить их страницы, это незаконно – zerkms
Это не для коммерческого использования. – Brent
@zerkms Его проблема, а не наша; и я не считаю, что это может быть признано незаконным для скрининга сайта, его можно считать фактически незаконным для использования указанных данных способами, которые его лицензия не позволяет. – Ben