How to convert an array to object in PHP?

前端 未结 30 2688
说谎
说谎 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

    The one I use (it is a class member):

    const MAX_LEVEL = 5; // change it as needed
    
    public function arrayToObject($a, $level=0)
    {
    
        if(!is_array($a)) {
            throw new InvalidArgumentException(sprintf('Type %s cannot be cast, array expected', gettype($a)));
        }
    
        if($level > self::MAX_LEVEL) {
            throw new OverflowException(sprintf('%s stack overflow: %d exceeds max recursion level', __METHOD__, $level));
        }
    
        $o = new stdClass();
        foreach($a as $key => $value) {
            if(is_array($value)) { // convert value recursively
                $value = $this->arrayToObject($value, $level+1);
            }
            $o->{$key} = $value;
        }
        return $o;
    }
    
    0 讨论(0)
  • 2020-11-22 03:23

    The easy way would be

    $object = (object)$array;
    

    But that's not what you want. If you want objects you want to achieve something, but that's missing in this question. Using objects just for the reason of using objects makes no sense.

    0 讨论(0)
  • 2020-11-22 03:23

    Multidimensional arrays into an object. this code is used for conversion of Bing search API try and catch method.

    try {
            // Perform the Web request and get the JSON response
            $context = stream_context_create($options);
            $results = file_get_contents($url . "?cc=" . $country . "&category=" . $type, false, $context);
            $results = json_decode($results);
            return response()->json($results);
        } catch (\Exception $e) {
            $results = array('value' => array(
                    (object) array(
                        "name" => "Unable to Retrive News",
                        "url" => "http://www.sample.com/",
                        "image" => (object) array("thumbnail" => (object) array("contentUrl" => "")),
                        "publishedAt" => "",
                        "description" => "")
                )
            );
            $results = (object) $results;
            return response()->json($results);
        }
    
    0 讨论(0)
  • 2020-11-22 03:25

    Here are three ways:

    1. Fake a real object:

      class convert
      {
          public $varible;
      
          public function __construct($array)
          {
              $this = $array;
          }
      
          public static function toObject($array)
          {
              $array = new convert($array);
              return $array;
          }
      }
      
    2. Convert the array into an object by casting it to an object:

      $array = array(
          // ...
      );
      $object = (object) $array;
      
    3. Manually convert the array into an object:

      $object = object;
      foreach ($arr as $key => $value) {
          $object->{$key} = $value;
      }
      
    0 讨论(0)
  • 2020-11-22 03:25

    Easy:

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

    Example:

    $array = array(
        'key' => array(
            'k' => 'value',
        ),
        'group' => array('a', 'b', 'c')
    );
    
    $object = json_decode(json_encode($array));
    

    Then, the following is true:

    $object->key->k === 'value';
    $object->group === array('a', 'b', 'c')
    
    0 讨论(0)
  • 2020-11-22 03:25

    Best Method in the WORLD :)

    function arrayToObject($conArray)
    {
        if(is_array($conArray)){
            /*
            * Return array converted to object
            * Using __FUNCTION__ (Magic constant)
            * for recursive call
            */
            return (object) array_map(__FUNCTION__, $conArray);
        }else{
            // Return object
            return $conArray;
        }
    }
    

    if you use different methods you will have problems. This is the best method. You have ever seen.

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