S
S
Shimpanze2020-05-16 04:51:21
PHP
Shimpanze, 2020-05-16 04:51:21

How to get all id values ​​from nested objects?

There is an object:

object(stdClass)#3 (13) {
  ["id"]=>
  int(111)
  ["attachments"]=>
  array(1) {
    [0]=>
    object(stdClass)#4 (2) {
      ["photo"]=>
      object(stdClass)#5 (9) {
        ["id"]=>
        int(222)
          ...
          ...

How to get all id's at any depth? The output needs an array of id [111, 222].

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-05-16
@Shimpanze

function getIds($obj) {
  $ids = [];

  if (isset($obj->id)) {
    $ids[] = $obj->id;
  }

  if (is_object($obj) || is_array($obj)) {
    foreach ($obj as $val) {
      array_push($ids, ...getIds($val));
    }
  }

  return $ids;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question