如何用php提取json数据?

时间:2016-12-20 07:12:02

标签: php json

我有来自API的json数据,我想将它们插入到我的数据库表中。我想在php中提取var app = angular.module('myapp', []); app.controller('MainCtrl', function($scope) { $scope.countries = ["USA","Canada"]; $scope.states = [{ "name": "Alabama", "countryId": "USA" }, { "name": "Alaska", "countryId": "USA" }, { "name": "Arizona", "countryId": "USA" }, { "name": "Alberta", "countryId": "Canada" }, { "name": "British columbia", "countryId": "Canada" }]; $scope.countryChange = function(){ $scope.allStates = []; angular.forEach($scope.states, function(value){ if($scope.country == value.countryId){ $scope.allStates.push(value.name); } }); } }); 但是当我尝试使用此代码时,它会给我错误。

$myJson
  

错误:foreach ($myJson as $mj){ echo $mj['math_score']; // echo $mj->math_score; <= error // echo $mj[0]->post->math_score; <= error // echo $mj->post->math_score; <= error }

我的json数据就像这样。

Invalid argument supplied for foreach()
抱歉我的语法不好,任何答案都将不胜感激。感谢

1 个答案:

答案 0 :(得分:0)

内置了php函数json_decode()

尝试

$json = '{"posts":[{"post":{"math_score":"85","history_score":"70"}}]}';

$json = json_decode($json);

echo $json->posts{0}->post->math_score;

默认情况下json_decode返回对象。如果你想要一个数组,那么你需要将第二个参数true传递给json_decode

尝试使用数组

$json = '{"posts":[{"post":{"math_score":"85","history_score":"70"}}]}';

$json = json_decode($json, true);

foreach ($json['posts'] as $mj)
{
    echo $mj['post']['math_score'];
}