简体   繁体   English

PHP:如何将数组转换为StdClass对象?

[英]PHP: How to turn an array into a StdClass object?

Is there a PHP function that will do this automatically? 是否有自动执行此操作的PHP函数?

if (is_array($array)) {
    $obj = new StdClass();
    foreach ($array as $key => $val){
        $obj->$key = $val;
    }
    $array = $obj;
}

Why not just cast it? 为什么不投这个呢?

$myObj = (object) array("name" => "Jonathan");
print $myObj->name; // Jonathan

If it's multidimensional, Richard Castera provides the following solution on his blog : 如果它是多维的,Richard Castera在他的博客上提供了以下解决方案:

function arrayToObject($array) {
  if(!is_array($array)) {
    return $array;
  }
  $object = new stdClass();
    if (is_array($array) && count($array) > 0) {
      foreach ($array as $name=>$value) {
        $name = strtolower(trim($name));
          if (!empty($name)) {
            $object->$name = arrayToObject($value);
          }
      }
      return $object; 
    } else {
      return FALSE;
    }
}

如果它是一维数组,则应该使用强制转换:

$obj = (object)$array;

This works for me 这适合我

if (is_array($array)) {
$obj = new StdClass();
foreach ($array as $key => $val){

    $key = str_replace("-","_",$key) 

    $obj->$key = $val;
}
$array = $obj;
}

make sure that str_replace is there as '-' is not allowed within variable names in php, as well as: 确保str_replace在那里,因为php中的变量名称中不允许使用' - ',以及:

Naming Rules for Variables 变量的命名规则

* A variable name must start with a letter or an underscore "_"
* A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )
* A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString)

So, since these are permitted in arrays, if any of them comes in the $key from the array you are converting, you will have nasty errors. 因此,由于这些是在数组中允许的,如果它们中的任何一个来自您要转换的数组的$ key,则会出现令人讨厌的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM