好的,我有以下代码从API获取json结果:
$userGuid = "2d7c4ca4-d1b6-4c2a-9106-33df1251d946";
$apiKey = "my_key";
function query($connectorGuid, $input, $userGuid, $apiKey, $additionalInput) {
$url = "https://api.import.io/store/connector/" . $connectorGuid . "/_query?_user=" . urlencode($userGuid) . "&_apikey=" . urlencode($apiKey);
$data = array("input" => $input);
if ($additionalInput) {
$data["additionalInput"] = $additionalInput;
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// Query for tile Bundesliga Stats
$result = query("73df0478-4e6e-4f78-9ab5-f9866ac7a531", array(
"webpage/url" => "http://msn.foxsports.com/foxsoccer/bundesliga/teams/1-fc-nurnberg/stats/5131",
), $userGuid, $apiKey, false);
var_dump($result);
这是打印出的一个结果(它会持续一段时间):
array(6) {
["offset"] => int(0)["results"] => array(24) {
[0] => array(11) {
["games_played"] => string(1)
"1" ["player_name"] => string(16)
"Patrick Rakovsky" ["goals"] => string(4)
"1.00" ["assists"] => string(1)
"1" ["yellow_cards"] => string(1)
"0" ["games_started"] => string(1)
"0" ["shots_on_goal"] => string(1)
"4" ["fouls_suffered"] => string(1)
"0" ["fouls_committed"] => string(1)
"0" ["red_cards"] => string(1)
"0" ["minutes_played"] => string(2)
"45"
}
那么我有这个循环得到" player_name"和"目标"从上面的结果:
$players = array();
foreach($result['results'] as $player){
$players[$player['player_name']] = $player['goals'];
}
foreach($players as $player => $goals){
echo "Player:" . $player . "Goals:" . $goals;
}
我对数组很新,所以我知道输出我想要的两列。但是,我想抓住并回应其余的结果,比如" assists",& #34; yellow_cards"等。非常感谢任何帮助。谢谢。
答案 0 :(得分:2)
如果你想获取所有字段,那么你可以将所有$ result ['结果']分配给$ player。
$players = $result['results']; //store all results in $players
foreach($players as $player){
echo "Player:" . $player['player_name']
. "Goals:" . $player['goals']
. "Assists:" . $player['assists'];
//access others
}
如果你想抓住一些字段
$players = array();
$keys_to_copy = array('player_name','goals','assists'); //define fields you want to copy
foreach($result['results'] as $player){
$player_copy = array();
foreach($keys_to_copy as $key) {
$player_copy[$key] = $player[$key];
}
$players[] = $player_copy;
}
foreach($players as $player){
echo "Player:" . $player['player_name']
. "Goals:" . $player['goals']
. "Assists:" . $player['assists'];
}