将数组索引数组转换为动态大小的多维数组中的值
Convert array of array indices to value in multidimensional array of dynamic size
我有一个数组如下:
test[
0 => 0,
1 => 2 ,
2 => 0,
3 => 2
]
上面的数组值是一个更大数组的索引的表示,所以我需要将这些值转换为另一个数组的索引,它将更大的数组映射到下面的目标:
test2[0][2][0][2]
我试过了:
$test3= array_flip ( $test )
工作正常,但不方便碰撞,因为我无法控制阵列,有什么帮助吗?
function arrayToIndex($array,$index) {
$element = $array;
for ($i = 0; $i < count($index); $i++) {
$element = $element[$index[$i]];
}
return $element;
}
$test = [[[[1],[2]],[[3],[4]]],[[[5],[6]],[[7],[8]]]];
$index = [0,1,0,0];
echo arrayToIndex($test,$index);
这是一个实现您要求的行为的函数。 $array
是要搜索的数组,$index
是索引数组。我建议您尝试一下这个示例,看看如何检索每个值。
所以在 head 之后我想出了以下功能来达到我的目的:
$mainarray = [
0 => [
0 =>[
0 => [
0 => 'one' ,
1 => 'two' ,
2 => 'three' ,
3 => 'four'
],
1 => [
0 => 'one' ,
1 => 'two' ,
2 => 'three' ,
3 => 'four'
]
]
]
]
然后下面这个数组的值作为我想要得到的$mainarray
上面的索引让我们说one
,
$arraywithseacrhindex = [
0 => 0 ,
1 => 0 ,
2 => 0 ,
3 => 0 ,
]
解决方案:
$array = $mainarray ;
$arr = $arraywithseacrhindex ;
$counter= count($arr)-1 ;
$result = array() ;
for($i=0; $i< $counter; $i++) {
if(empty( $result ) )
{
// first loop to put $result at per with $array
$result[$arr[$i]] = $array[$arr[$i]] ;
}else{
// this is the trick of the solution
$cResult = current($result);
unset($result);
$result = array() ;
$result[$arr[$i]] = $cResult[$arr[$i]] ;
}
}
var_dump($result);
希望对以后的人有所帮助。
我有一个数组如下:
test[
0 => 0,
1 => 2 ,
2 => 0,
3 => 2
]
上面的数组值是一个更大数组的索引的表示,所以我需要将这些值转换为另一个数组的索引,它将更大的数组映射到下面的目标:
test2[0][2][0][2]
我试过了:
$test3= array_flip ( $test )
工作正常,但不方便碰撞,因为我无法控制阵列,有什么帮助吗?
function arrayToIndex($array,$index) {
$element = $array;
for ($i = 0; $i < count($index); $i++) {
$element = $element[$index[$i]];
}
return $element;
}
$test = [[[[1],[2]],[[3],[4]]],[[[5],[6]],[[7],[8]]]];
$index = [0,1,0,0];
echo arrayToIndex($test,$index);
这是一个实现您要求的行为的函数。 $array
是要搜索的数组,$index
是索引数组。我建议您尝试一下这个示例,看看如何检索每个值。
所以在 head 之后我想出了以下功能来达到我的目的:
$mainarray = [
0 => [
0 =>[
0 => [
0 => 'one' ,
1 => 'two' ,
2 => 'three' ,
3 => 'four'
],
1 => [
0 => 'one' ,
1 => 'two' ,
2 => 'three' ,
3 => 'four'
]
]
]
]
然后下面这个数组的值作为我想要得到的$mainarray
上面的索引让我们说one
,
$arraywithseacrhindex = [
0 => 0 ,
1 => 0 ,
2 => 0 ,
3 => 0 ,
]
解决方案:
$array = $mainarray ;
$arr = $arraywithseacrhindex ;
$counter= count($arr)-1 ;
$result = array() ;
for($i=0; $i< $counter; $i++) {
if(empty( $result ) )
{
// first loop to put $result at per with $array
$result[$arr[$i]] = $array[$arr[$i]] ;
}else{
// this is the trick of the solution
$cResult = current($result);
unset($result);
$result = array() ;
$result[$arr[$i]] = $cResult[$arr[$i]] ;
}
}
var_dump($result);
希望对以后的人有所帮助。