我在PHP中使用web服务,但它返回了一个json,我无法访问特定的值,如CodSmaterial。。你能帮我吗??我试图使用:
$materia->GetResult->Materias->CodMateria;
我无法访问的结果:
string(934) "{"GetResult":{"Materias":[{"CodMateria":"001","Materia":"Math","paralelo":"A"},
{"CodMateria":"002","Materia":"Math2","paralelo":"B"},
{"CodMateria":"003","Materia":"Math3","paralelo":"C"},
{"CodMateria":"004","Materia":"Math4","paralelo":"D"}]}}"
使用json_decode()
。有多个codeMateria
,因此为了访问第一个使用:
$materia->GetResult->Materias[0]->CodMateria
根据文档,如果您想要一个关联数组,而不是json_decode中的对象,则需要指定以下代码:
json_decode($jsondata,true);
http://php.net/json_decode
根据您提到的内容,您可以使用json_decode
<?php
$jsonData = '{"GetResult":{"Materias":[{"CodMateria":"001","Materia":"Math","paralelo":"A"},
{"CodMateria":"002","Materia":"Math2","paralelo":"B"},
{"CodMateria":"003","Materia":"Math3","paralelo":"C"},
{"CodMateria":"004","Materia":"Math4","paralelo":"D"}]}}';
$materia = json_decode($jsonData);
echo $materia->GetResult->Materias[0]->CodMateria;
输出:
001
样品蒸发
或者,
您可以使用json_decode($jsonData, true);
将您的转换为数组。在这种情况下,你需要这样访问:
<?php
$jsonData = '{"GetResult":{"Materias":[{"CodMateria":"001","Materia":"Math","paralelo":"A"},
{"CodMateria":"002","Materia":"Math2","paralelo":"B"},
{"CodMateria":"003","Materia":"Math3","paralelo":"C"},
{"CodMateria":"004","Materia":"Math4","paralelo":"D"}]}}';
$materia = json_decode($jsonData, true);
echo $materia["GetResult"]["Materias"][0]["CodMateria"];
尝试使用json_decode
<?php
$strJson = '{"GetResult":{"Materias":[{"CodMateria":"001","Materia":"Math","paralelo":"A"},
{"CodMateria":"002","Materia":"Math2","paralelo":"B"},
{"CodMateria":"003","Materia":"Math3","paralelo":"C"},
{"CodMateria":"004","Materia":"Math4","paralelo":"D"}]}}';
$arrJson = json_decode($strJson);
foreach($arrJson->GetResult->Materias as $objResult)
{
echo "<br>".$objResult->CodMateria;
}
?>
这将给出如下输出:
001
002
003
004
以类似的方式,您也可以访问其他值。。!
例如
$objResult->Materia;
$objResult->paralelo;