从多个答案得到答案json

时间:2015-10-15 11:47:34

标签: php json

这是json(它可以是1到10个响应):

{"d":[{"__type":"OperatorDataContract:http:\/\/psgi.pts.se\/PTS_Number_Service","Name":"TeliaSonera Sverige AB","Number":"XXXX-XXXXX"},
{"__type":"OperatorDataContract:http:\/\/psgi.pts.se\/PTS_Number_Service","Name":"TeliaSonera Sverige AB","Number":"XXXX-XXXXX"},
{"__type":"OperatorDataContract:http:\/\/psgi.pts.se\/PTS_Number_Service","Name":"Tele2 Sverige AB","Number":"XXXX-XXXXX"}]}

当我得到1回复时,我有这个:

$str = file_get_contents($apilink);
$data = json_decode($str, true);
$operator = $data['d']['Name'];

然而,如果有多个答案,就像我们所展示的那样,它只会是空白的(可能是因为它找到了多个" Name")。 你怎么从回复中得到所有的名字?

2 个答案:

答案 0 :(得分:0)

你会得到这样的多重回复:

$data['d'][0]['Name'];
$data['d'][1]['Name'];
$data['d'][2]['Name'];

试试这个:

if (count($data['d']) > 1) {
   foreach($data['d'] as $result){
      $operator[] = $result['Name'];
   }
}

这里我们循环遍历数组,在一个名为$ operator的单个数组中获取多个名称。

答案 1 :(得分:0)

你需要的是foreach循环,这里是将吐出json响应中所有名称的样本。

$json = '{"d":[{"__type":"OperatorDataContract:http:\/\/psgi.pts.se\/PTS_Number_Service","Name":"TeliaSonera Sverige AB","Number":"XXXX-XXXXX"},
{"__type":"OperatorDataContract:http:\/\/psgi.pts.se\/PTS_Number_Service","Name":"TeliaSonera Sverige AB","Number":"XXXX-XXXXX"},
{"__type":"OperatorDataContract:http:\/\/psgi.pts.se\/PTS_Number_Service","Name":"Tele2 Sverige AB","Number":"XXXX-XXXXX"}]}';

$data = json_decode($json, true);

$operator = $data['d'];

foreach($operator as $value)
{
    echo $value['Name'].'<br>';

}

希望以上内容有意义,我建议您阅读更多关于foreach的内容,以便您可以清楚地了解如何以迭代方式使用数据