• 数组与对象相互转化


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

      

     


  • 相关阅读:
    Elasticsearch通关
    Zookeeper是什么
    手把手带你了解消息中间件(1)——基础
    为什么要分库分表
    mysql的innodb 引擎 表锁与行锁
    MySQL中Innodb的聚簇索引和非聚簇索引
    Redis主从和集群
    redis防止抢购商品超卖
    Laravel 核心--Facades 门面
    PHP数据库操作:使用ORM
  • 原文地址:https://www.cnblogs.com/SofuBlue/p/8082013.html
Copyright © 2020-2023  润新知