如何将这样的数组转换为对象?
[128] => Array
(
[status] => "Figure A.
Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution."
)
[129] => Array
(
[status] => "The other day at work, I had some spare time"
)
如何将这样的数组转换为对象?
[128] => Array
(
[status] => "Figure A.
Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution."
)
[129] => Array
(
[status] => "The other day at work, I had some spare time"
)
当前回答
递归是你的朋友:
function __toObject(Array $arr) {
$obj = new stdClass();
foreach($arr as $key=>$val) {
if (is_array($val)) {
$val = __toObject($val);
}
$obj->$key = $val;
}
return $obj;
}
其他回答
递归是你的朋友:
function __toObject(Array $arr) {
$obj = new stdClass();
foreach($arr as $key=>$val) {
if (is_array($val)) {
$val = __toObject($val);
}
$obj->$key = $val;
}
return $obj;
}
一个衬套
$object= json_decode(json_encode($result_array, JSON_FORCE_OBJECT));
你也可以通过在变量的左边添加(object)来创建一个新对象。
<?php
$a = Array
( 'status' => " text" );
var_dump($a);
$b = (object)$a;
var_dump($b);
var_dump($b->status);
http://codepad.org/9YmD1KsU
根据你需要的位置和访问对象的方式有不同的方法。
例如:只需对它进行类型转换
$object = (object) $yourArray;
然而,最兼容的方法是使用一个实用程序方法(还不是PHP的一部分),它实现了基于指定类型的字符串的标准PHP强制转换(或者忽略它,只是去引用值):
/**
* dereference a value and optionally setting its type
*
* @param mixed $mixed
* @param null $type (optional)
*
* @return mixed $mixed set as $type
*/
function rettype($mixed, $type = NULL) {
$type === NULL || settype($mixed, $type);
return $mixed;
}
您案例中的使用示例(在线演示):
$yourArray = Array('status' => 'Figure A. ...');
echo rettype($yourArray, 'object')->status; // prints "Figure A. ..."
使用json_encode是有问题的,因为它处理非UTF-8数据的方式。值得注意的是,json_encode/json_encode方法也将非关联数组作为数组。这可能是你想要的,也可能不是。我最近需要重新创建这个解决方案的功能,但没有使用json_ functions。这是我想到的:
/**
* 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;
}
}