zoukankan      html  css  js  c++  java
  • 数组与对象相互转化

    本文实例讲述了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);
    

      

     


  • 相关阅读:
    WPF的布局--DockPanel
    WPF的布局--StackPanel
    C#中的不可空类型转为可空类型
    linux下安装nodejs及npm
    HTML DOM 事件对象 ondragend 事件
    pc端页面在移动端显示问题
    css设置文字上下居中,一行文字居中,两行或多行文字同样居中。
    超简单的gif图制作工具
    Git创建与合并分支
    props default 数组/对象的默认值应当由一个工厂函数返回
  • 原文地址:https://www.cnblogs.com/SofuBlue/p/8082013.html
Copyright © 2011-2022 走看看