您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
一、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] <[<complet@163.com>]>
* @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"
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。