carla noriega
carla noriega

Reputation: 3

how to get the data of a json in php

I'm using web services in PHP but it returns a json that I can't access to an specific value like CodMateria.. Could you help me please?? I was trying to use:

$materia->GetResult->Materias->CodMateria;

The result that i can't access:

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"}]}}" 

Upvotes: 0

Views: 70

Answers (4)

Thamilhan
Thamilhan

Reputation: 13323

From what you have mentioned, you can use 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;

Outputs:

001

Sample Eval


Alternatively,

You can use json_decode($jsonData, true); to convert yours into array. In that case you need to access like this:

<?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"];

Upvotes: 0

Suyog
Suyog

Reputation: 2482

Try using 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;
}
?>

This will give output like below:

001

002

003

004

In similar way, you can access other values as well..!

e.g.

$objResult->Materia;
$objResult->paralelo;

Upvotes: 0

Naqash Malik
Naqash Malik

Reputation: 1816

Use json_decode(). There are multiple codeMateria so in order to access first one use:

$materia->GetResult->Materias[0]->CodMateria

Upvotes: 2

Mueyiwa Moses Ikomi
Mueyiwa Moses Ikomi

Reputation: 1142

As per the documentation, you need to specify if you want an associative array instead of an object from json_decode, this would be the code:

json_decode($jsondata, true);

http://php.net/json_decode

Upvotes: 1

Related Questions