0

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

4 Answers4

2

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

$materia->GetResult->Materias[0]->CodMateria
Naqash Malik
  • 1,707
  • 1
  • 12
  • 14
1

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

Mueyiwa Moses Ikomi
  • 1,069
  • 2
  • 12
  • 26
0

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"];
Thamilhan
  • 13,040
  • 5
  • 37
  • 59
0

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;
Community
  • 1
  • 1
Suyog
  • 2,472
  • 1
  • 14
  • 27