stdClass to array?

后端 未结 11 1759
情话喂你
情话喂你 2020-12-03 05:05

i have:

stdClass Object
(
    [0] => stdClass Object
        (
            [one] => aaa
            [two] => sss
        )

    [1] => stdClass O         


        
相关标签:
11条回答
  • 2020-12-03 05:27

    If you're using json_decode to convert that JSON string into an object, you can use the second parameter json_decode($string, true) and that will convert the object to an associative array.

    If not, what everybody else has said and just type cast it

    $array = (array) $stdClass;

    0 讨论(0)
  • 2020-12-03 05:33

    Your problem is probably solved since asking, but for reference, quick uncle-google answer:

    function objectToArray($d) {
      if(is_object($d)) {
        $d = get_object_vars($d);
      }
      if(is_array($d)) {
        return array_map(__FUNCTION__, $d); // recursive
      } else {
        return $d;
      }
    }
    

    Full article here. Note I'm not associated with the original author in any way.

    0 讨论(0)
  • function load_something () : \stdClass {
    
        $result = new \stdClass();
    
        $result->varA   = 'this is the value of varA';
        $result->varB   = 'this is the value of varB';
        $result->varC   = 'this is the value of varC';
    
        return $result;
    }
    
    $result = load_something();
    
    echo ($result instanceof stdClass)?'Object is stdClass':'Object is not stdClass';
    echo PHP_EOL;
    
    print_r($result);
    
    //directly extract a variable from stdClass 
    echo PHP_EOL . 'varA = ' . ($result->varA);
    
    //convert to array, then extract
    $array = (array)$result;
    echo PHP_EOL . 'varA = ' . $array['varA'];
    
    0 讨论(0)
  • 2020-12-03 05:42

    Of course you can typecast, $var = (array) $obj;, but I would suggest ArrayAccess to your class.

    By using ArrayAccess, you can then treat your objects and data as if it was an array, or natively as an object.

    0 讨论(0)
  • This one worked for me, The decoding and encoding makes for a regular array

    $array = json_decode(json_encode($object), True);

    0 讨论(0)
  • 2020-12-03 05:43

    stdClass is an object so u can access value from it like

    echo stdClass->one;
    
    0 讨论(0)
提交回复
热议问题