我创建了一个方法,允许我为值行分配键,并附加额外的键和值。
它将所有新键添加到键数组中,然后将所有新值添加到值数组中,然后组合所有键和值。
我如何缩小它,使它更小,更有效率?
$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);
}输出:
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
发布于 2014-08-21 18:53:54
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));
}发布于 2022-09-10 05:42:33
作为@havenard答案的一种现代化形式,我使用PHP7.4的箭头函数语法来避免对use()的需求,并使用数组联合操作符(+)来避免迭代的array_merge()调用。数组联合操作符是适当的,因为它将关联数组添加到另一个数组中。
代码:(演示)
var_export(
array_map(
fn($row) => array_combine($keys, $row) + $id,
$valores
)
);https://stackoverflow.com/questions/25433724
复制相似问题