如何将这样的数组转换为对象?

[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"
    )

当前回答

我用了很简单的方法,

    $list_years         = array();
    $object             = new stdClass();

    $object->year_id   = 1 ;
    $object->year_name = 2001 ;
    $list_years[]       = $object;

其他回答

它的方法很简单,这将为递归数组创建一个对象:

$object = json_decode(json_encode((object) $yourArray), FALSE);

我也有这个问题,但我注意到json_decode将JSON数组转换为对象。

所以,我通过使用json_encode($PHPArray)来实现我的解决方案,它返回对象的JSON字符串,然后我用Json_decode($string)解码字符串,它将返回一个完美的结构化对象。 速记

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

Or

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

CakePHP有一个递归的Set::map类,基本上是将数组映射到对象。为了使对象看起来像你想要的样子,你可能需要改变数组的样子。

http://api.cakephp.org/view_source/set/#line-158

最坏的情况下,您可能会从这个函数中得到一些想法。

快速攻击:

// assuming $var is a multidimensional array
$obj = json_decode (json_encode ($var), FALSE);

不漂亮,但很好用。

根据你需要的位置和访问对象的方式有不同的方法。

例如:只需对它进行类型转换

$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. ..."