【问题标题】:Convert array of array indices to value in multidimensional array of dynamic size将数组索引数组转换为动态大小的多维数组中的值
【发布时间】:2016-07-12 10:44:21
【问题描述】:

我有一个数组如下:

test[
0 => 0,
1 => 2 ,
2 => 0,
3 => 2
]

上面的数组值是一个更大数组的索引的表示,所以我需要将值转换为另一个数组的索引,它将映射更大的数组以达到下面的效果:

test2[0][2][0][2]

我试过了:

$test3= array_flip ( $test ) 

工作正常,但不方便碰撞,因为我无法控制数组,有什么帮助吗?

【问题讨论】:

  • 您正在尝试将元素数组转换为数组。换句话说,您正在尝试创建一个嵌套数组。没有内置的 php 函数来点他的。你必须自己写。
  • test2[test[0]][test[1]][test[2]][test[3]] 不工作?
  • @JamesPaterson 会起作用,但我不知道数组的长度是动态的
  • 好的 - 处理函数

标签: php arrays multidimensional-array indices


【解决方案1】:

所以在 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);

希望它对未来的人有所帮助。

【讨论】:

    【解决方案2】:
    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 是索引数组。我建议你试试这个例子,看看如何检索每个值。

    现场示例:http://ideone.com/fork/BzCjcK

    【讨论】:

    • returns 3 ,我的最终目标是获得一个数组索引表示,如您的示例中的 $index
    • 这是处理测试数据$test$index。您只需要复制该函数并在您的 OP 示例中将该函数调用为arrayToIndex($test2,$test)。它返回三个,因为那是 $test[0][1][0][0] 处的元素。
    • 再一次,$test2$test1 值的最终结果,我知道$test2 是我需要从$test 的值中得到$test2 的原因
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2019-02-10
    相关资源
    最近更新 更多