Home >php教程 >php手册 >php对象和数组相互转换的方法,php数组相互转换

php对象和数组相互转换的方法,php数组相互转换

WBOY
WBOYOriginal
2016-06-13 09:04:411097browse

php对象和数组相互转换的方法,php数组相互转换

本文实例讲述了php对象和数组相互转换的方法。分享给大家供大家参考。具体分析如下:

这里定义2个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);
print $obj->one; // output's "two"
$arr = object2array($obj);
print $arr['foo']; // output's bar

希望本文所述对大家的php程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn