-1

I am receiving a JSON string from an API, which I am then decoding into an array. The array is full of stdClass Objects and arrays, but I cannot seem to access the properties.

This is the array I have decoded from JSON and then called print_r on:

stdClass Object
(
[scannedDocument] => stdClass Object
    (
        [scanId] => 6188703b5450ed927159cbbbb223fc89
        [totalWords] => 7
        [totalExcluded] => 0
        [credits] => 1
        [creationTime] => 2019-10-21T10:33:18
    )

[results] => stdClass Object
    (
        [internet] => Array
            (
            )

        [database] => Array
            (
            )

        [batch] => Array
            (
            )

        [score] => stdClass Object
            (
                [identicalWords] => 0
                [minorChangedWords] => 0
                [relatedMeaningWords] => 0
                [aggregatedScore] => 0
            )

    )

[status] => 0

)

I am assuming I should access the first value of the array and then using -> to get to the object values like this:

$wordcount = $jsonResponse[0]->scannedDocument->totalWords;
$totalExcluded = $jsonResponse[0]->scannedDocument->totalExcluded;
$percent = $jsonResponse[0]->results->score->aggregatedScore;

But these variables are blank. I am tearing my hair out!

Any ideas please?

Dan
  • 1,154
  • 1
  • 7
  • 14
  • 1
    If you want an array, you can try `json_decode($json, true);` to decode at as an array rather than an object – Brett Gregson Oct 21 '19 at 10:42
  • 1
    _“This is the array”_ - if the debug output _starts_ with “stdClass Object”, then it is not an array … It is hard to tell if you meant this was just one single item _of_ that array here … or if you don’t know the difference in the first place? – 04FS Oct 21 '19 at 10:54
  • 1
    If that is your **entire** response i.e. the output of `print_r($jsonResponse)` then just remove the `[0]` from your code and it should work fine. – Nick Oct 21 '19 at 11:31
  • That worked perfectly Nick, thank you so much – Dan Oct 21 '19 at 17:16

1 Answers1

0

You can convert your object to array or stdClass and access it using one of those function according to object type

function ConvertToObject($array) {
    $object = new stdClass();
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $value = ConvertToObject($value);
        }
        if (isset($value)) {
            $object->$key = $value;
        }
    }
    return $object;
}
function ConvertToArray($obj) {
    if (is_object($obj))
        $obj = (array) $obj;
    if (is_array($obj)) {
        $new = array();
        foreach ($obj as $key => $val) {
            $new[$key] = ConvertToArray($val);
        }
    } else {
        $new = $obj;
    }
    return $new;
}