动态组合键和值的更好方法

时间:2014-08-21 18:43:38

标签: php

我创建了这个方法,它允许我为数组值赋值,让我为每个数组添加额外的键和值。

它将所有新键添加到键数组中,然后将所有新值添加到values数组中,然后组合所有键和值。

如何缩小它以使其更小更高效?

$valores = array(array("1","1","1","1"),array("2","2","2","2"));//array of values
$keys = array('k1','k2','k3','k4'); //array of keys
$id = array('SpecialKey' => 'SpecialValue');//new array of items I want to add

function formatarArray($arrValores,$arrKeys,$identificadores){
    foreach($identificadores as $k => $v){
        array_push($arrKeys, $k);
    }

    foreach($arrValores as $i => $arrValor)
    {
        foreach($identificadores as $k => $v){
         array_push($arrValor, $v);
         }
         $arrValores[$i] = array_combine($arrKeys, $arrValor);
    }
    print_r($arrValores);
}

输出:

Array ( 
[0]=>Array([k1]=>1 [k2] => 1 [k3] => 1 [k4] => 1 [SpecialKey] => SpecialValue) 
[1]=>Array([k1]=>2 [k2] => 2 [k3] => 2 [k4] => 2 [SpecialKey] => SpecialValue) 
) 

Viper-7(代码调试):
http://viper-7.com/hbE1YF

1 个答案:

答案 0 :(得分:0)

function formatarArray($arrValores, $arrKeys, $identificadores)
{
    foreach ($arrValores as &$arr)
        $arr = array_merge(array_combine($arrKeys, $arr), $identificadores);
    print_r($arrValores);
}

甚至可以在一行中完成......

function formatarArray($arrValores, $arrKeys, $identificadores)
{
    print_r(array_map(function ($arr) use ($arrKeys, $identificadores) { return array_merge(array_combine($arrKeys, $arr), $identificadores); }, $arrValores));
}