1

I am being give this object via an api. How can I get the status element from it? It just looks really unusual to me because it's root element is an id number. I can't seem to use $myObject->8772622 or $myObject->status and can't think of any other way to address the root of the object so I can get it's contents.

stdClass Object
(
    [8772622] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 8267788
                    [pattern_id] => 8772622
                    [status] => RENEWED
                    [begin_date] => 2019-12-11 16:00:00
                    [end_date] => 2019-12-12 10:00:00
                    [uuid] => 
                )

        )

)

Thanks,

Wittner

Wittner
  • 583
  • 5
  • 21

3 Answers3

0

Try this:

$myObjectAsArray = json_decode(json_encode($myObject), True)

Then access status as: $myObjectAsArray[8772622][0]['status']

0

You can use curly brace syntax to access properties with invalid names

<?php
$myObject = json_decode('{"8772622": [{"status": "RENEWED"}]}');

var_dump($myObject);
var_dump($myObject->{'8772622'}[0]->status);

Output:

object(stdClass)#2 (1) {
  ["8772622"]=>
  array(1) {
    [0]=>
    object(stdClass)#1 (1) {
      ["status"]=>
      string(7) "RENEWED"
    }
  }
}
string(7) "RENEWED"

Alternativley, you could cast the object to an array and access it by index number

$status = ((array)$myObject)[8772622][0]->status;

Probably, you got this object from using json_decode() on the API response. Set it's second argument to true to get an array instead of an object in the first place.

Ferdy Pruis
  • 1,073
  • 8
  • 9
  • Thanks Ferdy. This is correct. The CURL request returns the data as an object. There are a lot of hooks already into this CURL function so I've added the possibility to enter a flag for an array return, in which case I include the true parmeter. The data now cracks open like and egg and I can get all the fields :) Marking this as the correct answer. The ["8772622"] seems like an odd return from and api though? – Wittner Nov 20 '19 at 09:47
  • Just and addendum to this. Since you can't actually hard code the root number (8772622 in this case) you will have to get that somewhere in advance. This api will however use a predictable number. As it happens, I can know what this number will be, so my code is now: $status = $myObject[$current_id][0]->status; – Wittner Nov 21 '19 at 15:00
-1

try

$myObject->8772622[0]->status

before status you can see array.

  • Yeah, tried that with no success. No output at all. I'm thinking that PHP doesn't like the object's name being an int since you can't use a number as a var name in PHP. – Wittner Nov 19 '19 at 17:07