數組與對象相互轉化


 

 

 

 

本文實例講述了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 '<br><br>';
echo $s;
echo '<br><br>';
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 '<br><br>';

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

  

 

 



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM