javascriptphp数组对象互转类
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascriptphp数组对象互转类相关的知识,希望对你有一定的参考价值。
一、javascript:
- 代码:
/* @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<data[i].length;j++){ arr[j][i] = data[i][j] } } return arr } /* @desc:数组转对象 */ this.arrtoobj = function(){ var data = this.data var obj = {} for(var i in data){ for(var j in data[i]){ obj[j] = new Array() } } for(var i in data){ for(var j in data[i]){ obj[j][i] = data[i][j] } } return obj } }
- 测试:
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)
- 输出:
[ { id: 1, title: ‘title1‘, content: ‘content1‘ }, { id: 2, title: ‘title2‘, content: ‘content2‘ }, { id: 3, title: ‘title3‘, content: ‘content3‘ } ]
二、php:
- 代码:
/** * @desc:对象与数组互转类 * @author [Lee] <[<[email protected]>]> * @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; } }
- 测试:
$data = array( ‘id‘ => array(1,2), ‘title‘ => array(‘title1‘,‘title2‘), ‘content‘ => array(‘content1‘,‘content2‘) ); $arrobj = new arrobj($data); $ret = $arrobj->arrtoobj(); var_dump($ret);
- 输出:
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" } }
以上是关于javascriptphp数组对象互转类的主要内容,如果未能解决你的问题,请参考以下文章