这是我当前的PHP代码-仅导入一行数据,我需要它遍历动态变化的JSON-在不同时间可能是5行或10行。
我尝试了多种不同的方法来foreach()遍历数据,但没有一种起作用。
$jsonCont = file_get_contents('nba.json');
$data = json_decode($jsonCont, true);
$tip = $data['data'][0]['commence_time'];
$teama = $data['data'][0]['teams'][0];
$linea = $data['data'][0]['sites'][0]['odds']['spreads']['points'][0];
$teamb = $data['data'][0]['teams'][1];
$lineb = $data['data'][0]['sites'][0]['odds']['spreads']['points'][1];
$sql = "INSERT INTO nbagames(tip, teama, linea, teamb, lineb)
VALUES('$tip', '$teama', '$linea', '$teamb', '$lineb')";
if(!mysqli_query($conn,$sql))
{
die('Error : ' . mysql_error());
}
我需要在此代码中添加些什么,以便它遍历并获取所有数据而不仅仅是一行?
编辑:作为添加JSON数据的答复-这是一个示例-我需要获取所有游戏-但我不需要多个站点(如果有多个站点的赔率很高)
data: [
{
sport_key: "basketball_nba",
sport_nice: "NBA",
teams: [
"Charlotte Hornets",
"Washington Wizards"
],
commence_time: 1546128000,
home_team: "Washington Wizards",
sites: [
{
site_key: "mybookieag",
site_nice: "MyBookie.ag",
last_update: 1546136064,
odds: {
spreads: {
odds: [
1.8,
1.901
],
points: [
"3.5",
"-3.5"
]
}
}
}
],
sites_count: 1
},
{
sport_key: "basketball_nba",
sport_nice: "NBA",
teams: [
"Houston Rockets",
"New Orleans Pelicans"
],
commence_time: 1546128600,
home_team: "New Orleans Pelicans",
sites: [
{
site_key: "mybookieag",
site_nice: "MyBookie.ag",
last_update: 1546136064,
odds: {
spreads: {
odds: [
1.855,
1.855
],
points: [
"-6.5",
"6.5"
]
}
}
}
],
sites_count: 1
},
{
sport_key: "basketball_nba",
sport_nice: "NBA",
teams: [
"Atlanta Hawks",
"Cleveland Cavaliers"
],
commence_time: 1546130400,
home_team: "Atlanta Hawks",
sites: [
{
site_key: "mybookieag",
site_nice: "MyBookie.ag",
last_update: 1546136064,
odds: {
spreads: {
odds: [
1.855,
1.855
],
points: [
"-7.5",
"7.5"
]
}
}
}
],
sites_count: 1
},
{
sport_key: "basketball_nba",
sport_nice: "NBA",
teams: [
"Boston Celtics",
"Memphis Grizzlies"
],
commence_time: 1546132200,
home_team: "Memphis Grizzlies",
sites: [
{
site_key: "mybookieag",
site_nice: "MyBookie.ag",
last_update: 1546136064,
odds: {
spreads: {
odds: [
1.901,
1.855
],
points: [
"10.5",
"-10.5"
]
}
}
},
{
site_key: "bovada",
site_nice: "Bovada",
last_update: 1546136030,
odds: {
spreads: {
odds: [
1.952381,
1.87
],
points: [
"6.5",
"-6.5"
]
}
答案 0 :(得分:0)
您可以使用foreach:
$data = json_decode($jsonCont, true);
foreach($data['data'] as $line){
$tip = $line['commence_time'];
$teama = $line['teams'][0];
$linea = $line['sites'][0]['odds']['spreads']['points'][0];
$teamb = $line['teams'][1];
$lineb = $line['sites'][0]['odds']['spreads']['points'][1];
$sql = "INSERT INTO nbagames(tip, teama, linea, teamb, lineb)
VALUES('$tip', '$teama', '$linea', '$teamb', '$lineb')";
if(!mysqli_query($conn,$sql))
{
die('Error : ' . mysql_error());
}
}