How to convert an array to object in PHP?

前端 未结 30 3489
说谎
说谎 2020-11-22 02:48

How can I convert an array like this to an object?

[128] => Array
    (
        [status] => "Figure A.
 Facebook\'s horizontal scrollbars showing u         


        
30条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 03:21

    This one worked for me

      function array_to_obj($array, &$obj)
      {
        foreach ($array as $key => $value)
        {
          if (is_array($value))
          {
          $obj->$key = new stdClass();
          array_to_obj($value, $obj->$key);
          }
          else
          {
            $obj->$key = $value;
          }
        }
      return $obj;
      }
    
    function arrayToObject($array)
    {
     $object= new stdClass();
     return array_to_obj($array,$object);
    }
    

    usage :

    $myobject = arrayToObject($array);
    print_r($myobject);
    

    returns :

        [127] => stdClass Object
            (
                [status] => Have you ever created a really great looking website design
            )
    
        [128] => stdClass Object
            (
                [status] => Figure A.
     Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution.
            )
    
        [129] => stdClass Object
            (
                [status] => The other day at work, I had some spare time
            )
    

    like usual you can loop it like:

    foreach($myobject as $obj)
    {
      echo $obj->status;
    }
    

提交回复
热议问题