Search code examples
phparraysmultidimensional-arrayassociative-arrayarray-combine

Alter array rows to be associative and append an additional associative element


I've created a method that allows me to assign keys to rows of values, and appends extra keys and values.

It adds all the new keys to a keys array, then adds all new values to the values array, and then combines all the keys and values.

How can I shrink it to make it smaller and more efficient?

$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);
    }
    var_export($arrValores);
}

Output:

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(code debug):
http://viper-7.com/hbE1YF


Solution

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

    Could even be done in one line...

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