您好,登錄后才能下訂單哦!
一、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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。