How to convert an array to object in PHP?

前端 未结 30 3333
说谎
说谎 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:20

    Using json_encode is problematic because of the way that it handles non UTF-8 data. It's worth noting that the json_encode/json_encode method also leaves non-associative arrays as arrays. This may or may not be what you want. I was recently in the position of needing to recreate the functionality of this solution but without using json_ functions. Here's what I came up with:

    /**
     * Returns true if the array has only integer keys
     */
    function isArrayAssociative(array $array) {
        return (bool)count(array_filter(array_keys($array), 'is_string'));
    }
    
    /**
     * Converts an array to an object, but leaves non-associative arrays as arrays. 
     * This is the same logic that `json_decode(json_encode($arr), false)` uses.
     */
    function arrayToObject(array $array, $maxDepth = 10) {
        if($maxDepth == 0) {
            return $array;
        }
    
        if(isArrayAssociative($array)) {
            $newObject = new \stdClass;
            foreach ($array as $key => $value) {
                if(is_array($value)) {
                    $newObject->{$key} = arrayToObject($value, $maxDepth - 1);
                } else {
                    $newObject->{$key} = $value;
                }
            }
            return $newObject;
        } else {
    
            $newArray = array();
            foreach ($array as $value) {
                if(is_array($value)) {
                    $newArray[] = arrayToObject($value, $maxDepth - 1);
                } else {
                    $newArray[] = $value;
                }                
            }
            return $newArray;
        }
    }
    

提交回复
热议问题