我收到"非法字符串偏移"具有我尝试访问的密钥的数组上的错误:
PHP版本5.5.12
这会导致错误:
$avg = $season['avg'];
这是var_dump($ season)的结果:
array (size=38)
'hr' => string '4' (length=1)
'gidp' => string '2' (length=1)
'irs' => string '0' (length=1)
'np' => string '819' (length=3)
'team_count' => string '1' (length=1)
'era' => string '2.13' (length=4)
'sport_code' => string 'mlb' (length=3)
'sho' => string '0' (length=1)
'bk' => string '0' (length=1)
'sport_id' => string '1' (length=1)
'sv' => string '0' (length=1)
'avg' => string '.216' (length=4)
'whip' => string '0.88' (length=4)
'bb' => string '6' (length=1)
'ir' => string '0' (length=1)
'g' => string '9' (length=1)
'so' => string '39' (length=2)
'tbf' => string '244' (length=3)
'wp' => string '1' (length=1)
'sport' => string 'MLB' (length=3)
'l' => string '2' (length=1)
'svo' => string '0' (length=1)
'hb' => string '3' (length=1)
'h' => string '50' (length=2)
'ip' => string '63.1' (length=4)
'w' => string '4' (length=1)
's' => string '561' (length=3)
'ao' => string '46' (length=2)
'season' => string '2014' (length=4)
'r' => string '17' (length=2)
'go_ao' => string '2.17' (length=4)
'cg' => string '1' (length=1)
'player_id' => string '218596' (length=6)
'ab' => string '231' (length=3)
'gs' => string '9' (length=1)
'ibb' => string '1' (length=1)
'er' => string '15' (length=2)
'go' => string '100' (length=3);
这个数组被从一个更大的数组中剥离出来,该数组是通过在Web请求上使用json_decode创建的。我能够访问父数据数组来提取它。
我不知所措。我试过去投它。 gettype返回'数组'。任何想法都将不胜感激。
由于
//编辑:
我简化了上述问题。这是一个更准确的例子:
public function getPitcherAvg($id)
{
$stats = $this->getPitcherStats($id);
$stats = $stats['sport_pitching_composed']['sport_pitching_agg']['queryResults']['row'];
foreach ($stats as $season)
{
if ($season['season'] == 2014)
{
$avg = $season['avg'];
}
}
return $avg;
}
public function getPitcherStats($id)
{
$year = date("Y");
$url = "http://mlb.mlb.com/lookup/json/named.sport_pitching_composed.bam?game_type=%27R%27&sport_code=%27mlb%27&sort_by=%27season_asc%27&player_id={$id}&sport_pitching_composed.season=2014";
$json = file_get_contents($url);
return json_decode($json, true);
}
答案 0 :(得分:0)
事实证明我的数据并非始终如一(有时候数组没有嵌套)。
通过更改:
修正了它public function getPitcherAvg($id)
{
$stats = $this->getPitcherStats($id);
$stats = $stats['sport_pitching_composed']['sport_pitching_agg']['queryResults']['row'];
foreach ($stats as $season)
{
if ($season['season'] == 2014)
{
$avg = $season['avg'];
}
}
return $avg;
}
对此:
public function getPitcherAvg($id)
{
$stats = $this->getPitcherStats($id);
$seasons = $stats['sport_pitching_composed']['sport_pitching_agg']['queryResults']['row'];
foreach ($seasons as $key => $season)
{
if (!is_array($season))
{
if ($key == 'avg') $avg = $season;
}
elseif ($season['season'] == 2014)
{
$avg = $season['avg'];
}
}
return $avg;
}