我有多维数组
$testarray=Array
(
1 => Array
(
0 => 'A',
1 => 'B'
),
2 => Array
(
0 => 'A',
1 => 'C'
),
3 => Array
(
0 => 'A',
1 => 'C',
2 => 'D'
),
4 => Array
(
0 => 'A',
1 => 'C',
2 => 'E'
),
5 => Array
(
0 => 'X',
1 => 'Y'
),
6 => Array
(
0 => 'X',
1 => 'Y',
2 => 'Z'
),
7 => Array
(
0 => 'X',
1 => 'Y',
2 => 'ZZ'
),
8 => Array
(
0 => 'P',
1 => 'Q'
),
9 => Array
(
0 => 'P',
1 => 'Q',
2 => 'R'
),
10 => Array
(
0 => 'P',
1 => 'Q',
2 => 'R',
3 => 'S'
)
);
我需要使用$testarray
(维数组)生成以下数组:
array(A=array(B, C=array(D,E)),
X=array(Y=>array(Z,ZZ)),
P=array(Q=>array(R=>array(S))
答案 0 :(得分:0)
至少在我使用的PHP版本中,您可以执行类似
的操作$testArray = Array(
1 => Array(
'A'=> Array(
//Value of A here
)
'B' => Array(
//Value of B here
)
);
要访问它们,您可以写
$testArray[1]['A'];
如果你可以改变$ testArray的值,这应该有帮助。
答案 1 :(得分:0)
这应该有效。任何改进(和解释)将不胜感激。
foreach( $testarray as $values ) {
$depth = count($values);
$ref =& $array;
for( $i=0; $i<$depth; $i++ ) {
if( $i == $depth-1 ) {
$ref[] = $values[$i];
}
else {
if( !is_array( $ref ) || !array_key_exists( $values[$i], $ref ) ) {
$ref[$values[$i]] = array();
}
if( ( $key = array_search( $values[$i], $ref ) ) !== FALSE ) {
unset( $ref[$key] );
}
$ref =& $ref[$values[$i]];
}
}
}
输出:
array
'A' =>
array
0 => string 'B' (length=1)
'C' =>
array
0 => string 'D' (length=1)
1 => string 'E' (length=1)
'X' =>
array
'Y' =>
array
0 => string 'Z' (length=1)
1 => string 'ZZ' (length=2)
'P' =>
array
'Q' =>
array
'R' =>
array
0 => string 'S' (length=1)