PHP Print keys from an object?

前端 未结 5 902
眼角桃花
眼角桃花 2021-01-07 18:07

I have an object BIRD and then there is [0] through [10] and each number has a subheading like \"bug\" or \"beetle\" or \"gnat\" and a value for each of those.

I wan

相关标签:
5条回答
  • 2021-01-07 18:18

    I could be wrong but try to use array_keys using a object as parameter. I believe that is possible in php. http://php.net/manual/en/function.array-keys.php

    Anyway, read about reflection.

    0 讨论(0)
  • 2021-01-07 18:20

    Similar to brenjt's response, this uses PHP's get_object_vars instead of type casting the object.

    $array = get_object_vars($object);
    $properties = array_keys($array);
    
    0 讨论(0)
  • 2021-01-07 18:21

    If the 'object' is actually an associative array rather than a true object then array_keys() will give you what you need without warnings or errors.

    On the other hand, if your object is a true object, then you will get a warning if you try use array_keys() directly.

    You can extract the key-value pairs from an object as an associative array with get_object_vars(), you can then get the keys from this with array_keys():

    $keysFromObject = array_keys(get_object_vars($anObject));
    
    0 讨论(0)
  • 2021-01-07 18:39

    Looks like array_keys might have stopped working on objects but, amazingly, the foreach construct works, at least on a php stdClass object.

    $object = new stdClass();
    $object->a = 20;
    $object->b = "hello";
    $keys = array_keys($object);
    // array_keys returns null. PHP Version 7.3.3 windows
    foreach($object as $key=>$value)
    {
         // but this works
         echo("key:" . $key . " value:" . $value . "\n");
    }
    
    0 讨论(0)
  • 2021-01-07 18:41

    You could easily do it by type casting the object:

    $keys = array_keys((array)$BIRD);

    0 讨论(0)
提交回复
热议问题