将值数组转换为嵌套的关联数组

时间:2018-11-10 20:33:19

标签: php associative-array

php create multidimensional array from flat one

对此进行了尝试,但是倒数计算不起作用,因为我需要按照数组的原始顺序从头到尾移动。

我有一个简单的数组:

0 => Item #1
1 => Item #2 
2 => Item #3

我需要像上面这样创建一个关联数组:

Item #1 
  => Item #2 
    => Item #3

每个值都成为父项的键的地方。这必须在while循环中完成,而不要递归。它必须向前移动,循环将为验证目的而进行前瞻,因此原始命令势在必行

谢谢

编辑-这给了我预期的结果,我只是无法了解如何在主循环中执行此操作|

array:3 [
  0 => "workorder"
  1 => "company"
  2 => "name"
]

$array['workorder'] = [];
$temp = &$array['workorder'];
$temp['company'] = [];

$temp2 = &$temp['company'];
$temp2['name'] = [];

dump($array);
exit;

编辑2 |主循环

$type = current($types);
while (array_key_exists($type, $this->types)) {
    $nextType = next($types);

    // ... do stuff 

    $type = $nextType;
}

return $array;

1 个答案:

答案 0 :(得分:0)

尝试

// This array contain the keys for associative array
    $arrayKeys = ['name1', 'name2', 'name3'];

    // This array contain the values for associative array
    $arrayItems = ['item1', 'item2', 'item3'];

    // this array will be the associative array
    $newArray = [];      
    $count = count($arrayKeys) -1;
    while( $count >= 0 ){
        $newArray[ $arrayKeys[$count] ] = $arrayItems[$count];
        echo '<Br>';
        $count--;
    }