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

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

当前回答

我肯定会用这样一种干净的方式:

<?php

class Person {

  private $name;
  private $age;
  private $sexe;

  function __construct ($payload)
  {
     if (is_array($payload))
          $this->from_array($payload);
  }


  public function from_array($array)
  {
     foreach(get_object_vars($this) as $attrName => $attrValue)
        $this->{$attrName} = $array[$attrName];
  }

  public function say_hi ()
  {
     print "hi my name is {$this->name}";
  }
}

print_r($_POST);
$mike = new Person($_POST);
$mike->say_hi();

?>

如果你提交:

你会得到这个:

我发现这更符合逻辑的比较以上的答案从对象应该用于他们的目的(封装可爱的小对象)。

此外,使用get_object_vars确保在被操纵的对象中没有创建额外的属性(您不希望汽车有姓,也不希望人有4个轮子)。

其他回答

多维数组转换为对象。此代码用于转换必应搜索API的尝试和捕获方法。

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);
    }

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

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

在最简单的情况下,将数组“强制转换”为对象可能就足够了:

$object = (object) $array;

另一个选择是实例化一个标准类作为一个变量,循环遍历你的数组,同时重新分配值:

$object = new stdClass();
foreach ($array as $key => $value)
{
    $object->$key = $value;
}

正如Edson Medina指出的,一个真正干净的解决方案是使用内置的json_函数:

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

这也(递归地)将所有子数组转换为对象,这可能是你想要的,也可能不是。不幸的是,它比循环方法有2-3倍的性能损失。

警告!(感谢Ultra的评论):

不同环境上的json_decode以不同的方式转换UTF-8数据。我最终在当地得到了“240.00”的值,在生产中得到了“240”——巨大的灾难。此外,如果转换失败,字符串get返回为NULL

通过使用(array)和(object)作为前缀,可以简单地将对象数组转换为标准数组,反之亦然

<?php
//defining an array
$a = array('a'=>'1','b'=>'2','c'=>'3','d'=>'4');

//defining an object array
$obj = new stdClass();
$obj->a = '1';
$obj->b = '2';
$obj->c = '3';
$obj->d = '4';

print_r($a);echo '<br>';
print_r($obj);echo '<br>';

//converting object array to array
$b = (array) $obj;
print_r($b);echo '<br>';

//converting array to object
$c = (object) $a;
print_r($c);echo '<br>';
?>
function object_to_array($data)
{
    if (is_array($data) || is_object($data))
    {
        $result = array();
        foreach ($data as $key => $value)
        {
            $result[$key] = object_to_array($value);
        }
        return $result;
    }
    return $data;
}

function array_to_object($data)
{
    if (is_array($data) || is_object($data))
    {
        $result= new stdClass();
        foreach ($data as $key => $value)
        {
            $result->$key = array_to_object($value);
        }
        return $result;
    }
    return $data;
}