简体   繁体   中英

how to check if an array object contains an associative array in php?

Here is an array object that contains an array [body]. How do I get to know that this object has array inside and give me it's keys?

Array
(
    [6] => stdClass Object
        (
            [vid] => 6
            [uid] => 1
            [title] => om
            [log] => 
            [status] => 1
            [comment] => 2
            [promote] => 0
            [sticky] => 0
            [nid] => 6
            [type] => article
            [language] => und
            [created] => 1436514497
            [changed] => 1438003101
            [tnid] => 0
            [translate] => 0
            [revision_timestamp] => 1438003101
            [revision_uid] => 1
            [body] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value]

You need to check whether the object has body property, which is array and which should not be empty .

And fetch the keys it all three conditions fulfill.

Use is_array( ), array_keys() and isset()

if (isset($obj->body) && is_array($obj->body) && ! empty($obj->body)) {
  // yes it has
  $keys = array_keys($obj->body);
}
else {
  // either body is not there or body is empty. 
}

EDIT:

Check if any of the object properties is an array and return its keys.

foreach (get_object_vars($obj) as $var) {
  if (gettype($var) == 'array') {
    $keys = array_keys($var);
  }
}

Considering $main_array as your given result. Try this

if( is_array($main_array->body) )
{
// do your process
}

Check if it is an array with:

http://php.net/manual/de/function.is-array.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM