一、javascript:

  1. 代码:
    /*
    @desc:数组和对象互转类
    @param data 待转换的数据
    */
    function arrobj(data){
    this.data = data
    /*
     @desc:对象转数组
     */
    this.objtoarr = function(){
        var data = this.data
        var arr = new Array()
        for(var i in data){
            for(var j in data[i]){
                arr[j] = {}
            }
        }
        for(var i in data){
            for(var j=0;j
  2. 测试:
    var data = {
    id:[1,2,3],
    title:['title1','title2','title3'],
    content:['content1','content2','content3']
    }
    var arrobj = new arrobj(data)
    var ret = arrobj.objtoarr()
    console.log(ret)
  3. 输出:
    [ { id: 1, title: 'title1', content: 'content1' },
    { id: 2, title: 'title2', content: 'content2' },
    { id: 3, title: 'title3', content: 'content3' } ]

    二、php:

  4. 代码:
    /**
    * @desc:对象与数组互转类
    * @author [Lee] <[]>
    * @property
    *      data 传入的数据
    * @method
    *      objtoarr  对象转数组
    *      arrtoobj  数组转对象
    */
    class arrobj{
    private $data;
    /*
     @desc:构造方法,实例化待转换数据
     */
    public function __construct($data){
        $this->data = $data;
    }
    /*
     @desc:对象转数组
     */
    public function objtoarr(){
        $data = $this->data;
        $arr = array();
        foreach($data as $k=>$v){
            foreach($v as $k1=>$v1){
                $arr[$k1][$k] = $v1;
            }
        }
        return $arr;
    }
    /*
     @desc:数组转对象
     */
    public function arrtoobj(){
        $data = $this->data;
        $obj = array();
        foreach($data as $k=>$v){
            foreach($v as $k1=>$v1){
                $arr[$k1][$k] = $v1;
            }
        }
        return $arr;
    }
    }
  5. 测试:
    $data = array(
        'id' => array(1,2),
        'title' => array('title1','title2'),
        'content' => array('content1','content2')
    );
    $arrobj = new arrobj($data);
    $ret = $arrobj->arrtoobj();
    var_dump($ret);
  6. 输出:
    array(2) {
    [0]=>
    array(3) {
    ["id"]=>
    int(1)
    ["title"]=>
    string(6) "title1"
    ["content"]=>
    string(8) "content1"
    }
    [1]=>
    array(3) {
    ["id"]=>
    int(2)
    ["title"]=>
    string(6) "title2"
    ["content"]=>
    string(8) "content2"
    }
    }