本文实例讲述了php实现数组纵向转横向并过滤重复值的方法。分享给大家供大家参考,具体如下:
一、问题
有数组:
1
2
3
4
5
|
array (
6=> array (5=> '黑xx' , 42=> 'XXL' ),
7=> array (5=> '黑xx' , 40=> 'XL' ),
8=> array (8=> '灰' , 40=> 'XL' ),
);
|
要求转换成如下结果(数组纵向转横向并过滤重复值):
1
2
3
4
|
array (
0=> array (5=> '黑xx' , 8=> '灰' ),
1=> array (42=> 'XXL' , 40=> 'XL' ),
);
|
二、解决方法:
方法1:
1
2
3
4
5
6
7
8
9
10
11
12
|
$a = array (
6=> array (5=> '黑xx' , 42=> 'XXL' ),
7=> array (5=> '黑xx' , 40=> 'XL' ),
8=> array (8=> '灰' , 40=> 'XL' ),
);
foreach ( $a as $r ) {
$b [key( $r )] = current( $r );
next( $r );
$c [key( $r )] = current( $r );
}
$b = array ( $b , $c );
print_r( $b );
|
方法2:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
$arr = array (
6=> array (5=> '黑xx' , 42=> 'XXL' ),
7=> array (5=> '黑xx' , 40=> 'XL' ),
8=> array (8=> '灰' , 40=> 'XL' ),
);
$result = array ();
foreach ( $arr as $a ){
$keys = array_keys ( $a );
$vals = array_values ( $a );
$result [0][ $keys [0]] = $vals [0];
$result [1][ $keys [1]] = $vals [1];
}
print_r( $result );
|
最简单的写法:
1
2
3
4
5
6
7
8
9
10
|
$a = array (
6=> array (5=> '黑xx' , 42=> 'XXL' ),
7=> array (5=> '黑xx' , 40=> 'XL' ),
8=> array (8=> '灰' , 40=> 'XL' ),
);
foreach ( $a as $r ) {
$i = 0;
while (list( $k , $v ) = each( $r )) $b [ $i ++][ $k ] = $v ;
}
print_r( $b );
|
最终运行结果均为:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
Array
(
[0] => Array
(
[5] => 黑xx
[8] => 灰
)
[1] => Array
(
[42] => XXL
[40] => XL
)
)
|
希望本文所述对大家PHP程序设计有所帮助。