数组与对象相互转化

 

 

 

 

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

这里定义2个php匿名对象和数组相互转换的函数,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 ;
}

用法示例如下:

?
1
2
3
4
5
$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
对象转化为数组
$conn=mysqli_connect('localhost','root','','cf');
$sql="select * from dis where id=81";
$rs=mysqli_query($conn,$sql);
$s=$rs->num_rows;
var_dump($rs);
echo '

'; echo $s; echo '

'; function object_to_array($obj) { $obj = (array)$obj; foreach ($obj as $k => $v) { if (gettype($v) == 'resource') { return; } if (gettype($v) == 'object' || gettype($v) == 'array') { $obj[$k] = (array)object_to_array($v); } } return $obj; } $array=object_to_array($rs); var_dump($array); echo '

'; $conn=mysql_connect('localhost','root',''); mysql_query('set names utf8'); mysql_query('use cf'); $rs=mysql_query('select count(*) from dis where id=81',$conn); var_dump($rs);

  

 

 


转载于:https://www.cnblogs.com/SofuBlue/p/8082013.html

你可能感兴趣的:(数组与对象相互转化)