javascript与php一维数组与二维数组互转
发表于:2024-11-24 作者:热门IT资讯网编辑
编辑最后更新 2024年11月24日,一、php:一维转二维:a. 代码:/*@desc:一维数组转二维数组@param data 需要转换的数组@param key 主键@return ret 转换后的数组*/function onet
一、php:
- 一维转二维:
a. 代码:/*@desc:一维数组转二维数组@param data 需要转换的数组@param key 主键@return ret 转换后的数组*/function onetomore($data,$key){$ret = array();foreach($data as $v){ $arr = array(); foreach($v as $k1=>$v1){ if($k1 != $key){ $arr[$k1] = $v1; } } $ret[$v[$key]][] = $arr;}return $ret;}
b. 测试:
$data = array(array( 'user_id' => 1, 'role_id' => 1, 'user_nick' => 'a'),array( 'user_id' => 2, 'role_id' => 1, 'user_nick' => 'b'),array( 'user_id' => 3, 'role_id' => 2, 'user_nick' => 'c'));$ret = onetomore($data,'role_id');var_dump($ret);
c. 输出:
array(2) {[1]=>array(2) {[0]=>array(2) { ["user_id"]=> int(1) ["user_nick"]=> string(1) "a"}[1]=>array(2) { ["user_id"]=> int(2) ["user_nick"]=> string(1) "b"}}[2]=>array(1) {[0]=>array(2) { ["user_id"]=> int(3) ["user_nick"]=> string(1) "c"}}}
- 二维转一维:
a. 代码:/*@desc:二维数组转一维数组@param data 需要转换的数组@param key 主键@return ret 转换后的数组*/function moretoone($data,$key){$ret = array();$count = 0;foreach($data as $k=>$v){ foreach($v as $v1){ $ret[$count] = $v1; $ret[$count][$key] = $k; $count ++; }}return $ret;}
b. 测试:
$data = array(1 => array( array( "user_id" => 1, "user_nick" => 'a' ), array( "user_id" => 2, "user_nick" => 'b' )),2 => array( array( "user_id" => 3, "user_nick" => 'c' )));$ret = moretoone($data,'role_id');var_dump($ret);
c. 输出:
array(3) {[0]=>array(3) {["user_id"]=>int(1)["user_nick"]=>string(1) "a"["role_id"]=>int(1)}[1]=>array(3) {["user_id"]=>int(2)["user_nick"]=>string(1) "b"["role_id"]=>int(1)}[2]=>array(3) {["user_id"]=>int(3)["user_nick"]=>string(1) "c"["role_id"]=>int(2)}}
二、javascript:
- 一维转二维:
a. 代码:/*@desc:一维数组转二维数组@param data 需要转换的数组@param key 主键@return ret 转换后的数组*/function onetomore(data,key){var ret = {}for(var i in data){ ret[data[i][key]] = new Array()}for(var i in data){ var arr = {} for(var j in data[i]){ if(j != key){ arr[j] = data[i][j] } } ret[data[i][key]].push(arr)}return ret}
b. 测试:
var data = new Array( { 'uesr_id':1, 'role_id':1, 'user_nick':'a' }, { 'uesr_id':2, 'role_id':1, 'user_nick':'b' }, { 'uesr_id':3, 'role_id':2, 'user_nick':'c' })var ret = onetomore(data,'role_id')console.log(ret)
c. 输出:
{ '1': [ { uesr_id: 1, user_nick: 'a' }, { uesr_id: 2, user_nick: 'b' } ],'2': [ { uesr_id: 3, user_nick: 'c' } ] }
- 二维转一维:
a. 代码:/*@desc:二维数组转一维数组@param data 需要转换的数组@param key 主键@return ret 转换后的数组*/function moretoone(data,key){var ret = new Array()var count = 0for(var i in data){ ret[count] = {} for(var j in data[i]){ ret[count] = data[i][j] ret[count][key] = i count ++ }}return ret}
b. 测试:
var data = {1:new Array( { 'user_id':1, 'user_nick':'a' }, { 'user_id':2, 'user_nick':'b' } ),2:new Array( { 'user_id':3, 'user_nick':'c' } )}var ret = moretoone(data,'role_id')console.log(ret)
c. 输出:
[ { user_id: 1, user_nick: 'a', role_id: '1' },{ user_id: 2, user_nick: 'b', role_id: '1' },{ user_id: 3, user_nick: 'c', role_id: '2' } ]