将单维PHP数组转换为多维数组

时间:2016-08-19 08:35:45

标签: php arrays

如何在PHP中将单维数组转换为多维数组?假设你有这样的东西

$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';

你想要一个函数将它转换成

$array['breakfast'] = 'milk';
$array['meal']['firstdish'] = 'pasta';
$array['meal']['seconddish']['maincourse'] = 'veal';
$array['meal']['seconddish']['dressing'] = 'fries';
$array['meal']['dessert'] = 'pie';

同样的功能当然应该转换

$tire['ean'] = '3286347717116';
$tire['brand.maker'] = 'BRIDGESTONE';
$tire['brand.model.name'] = 'POTENZA';
$tire['brand.model.variant'] = 'RE 040 RFT * SZ';

$tire['ean'] = '3286347717116';
$tire['brand']['maker'] = 'BRIDGESTONE';
$tire['brand']['model']['name'] = 'POTENZA';
$tire['brand']['model']['variant'] = 'RE 040 RFT * SZ';

我正在考虑使用explode,然后对结果进行评估,但是eval总是感觉像是在欺骗我,我想这会让我的代码不能在HipHop中运行。

我想要这样做的原因是我必须将许多不同的表从数据库导出到XML文件中,并且我已经有一个强大的函数将多维数组转换为XML。

2 个答案:

答案 0 :(得分:0)

像这样:

function build(array &$trg, array $k,$key,$value) {
    $p = &$trg;
    while ( !empty($k) ) {
        $nk = array_shift($k);
        if ( !isset($p[$nk]) ) {
            $p[$nk] = [];
        }
        $p = &$p[$nk];
    }
    $p[$key] = $value;
    return $p;
}

$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';

$out = [];
foreach ($array as $key => $value ) {
       $path = explode('.',$key);
       $last = array_pop($path);
       build($out,$path,$last,$value);
}

print_r($out);

答案 1 :(得分:0)

您使用explode走在正确的轨道上,但没有必要使用eval。一旦你获得了可用的密钥,你就可以循环遍历它们并逐步将指针分配到一个新的数组中:

<?php
$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';

$result = [];
$target = null;

foreach ($array as $key => $value) {
    // Start by targeting the base of our resulting array
    $target =& $result;

    // Break the keys apart into pieces
    $keyParts = explode('.', $key);

    // Assign new target based on indexing into the result array one "piece" at a time
    while ($part = array_shift($keyParts)) {
        $target =& $target[$part];
    }

    // Finally, assign the value to our target
    $target = $value;
}

请参阅https://eval.in/625627