Loading

ORM要用到的数组转对象和对象转数组函数

<?php 

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

function object2array($object) {
  if (is_object($object)) {
    foreach ($object as $key => $value) {
      $array[$key] = $value;
    }
  }
  else {
    $array = $object;
  }
  return $array;
}


$array = array('foo' => 'bar','one' => 'two','three' => 'four');
$obj = array2object($array);
$arr = object2array($obj);

var_dump($obj);
echo('<br>');
var_dump($arr);

运行结果:

object(stdClass)#1 (3) {
  ["foo"]=>
  string(3) "bar"
  ["one"]=>
  string(3) "two"
  ["three"]=>
  string(4) "four"
}
<br>array(3) {
  ["foo"]=>
  string(3) "bar"
  ["one"]=>
  string(3) "two"
  ["three"]=>
  string(4) "four"
}

 

posted @ 2016-10-07 19:06  哈利路亚健儿奋起步伐  阅读(590)  评论(0编辑  收藏  举报