Php 动态组合键和值的更好方法
我创建了这个方法,它允许我将键分配给数组值,并允许我向每个数组添加额外的键和值。Php 动态组合键和值的更好方法,php,Php,我创建了这个方法,它允许我将键分配给数组值,并允许我向每个数组添加额外的键和值。它将所有新键添加到键数组,然后将所有新值添加到值数组,然后将所有键和值合并。 我如何缩小它以使其更小、更高效 $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('SpecialK
它将所有新键添加到键数组,然后将所有新值添加到值数组,然后将所有键和值合并。
我如何缩小它以使其更小、更高效
$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(代码调试):甚至可以在一行中完成
function formatarArray($arrValores, $arrKeys, $identificadores)
{
print_r(array_map(function ($arr) use ($arrKeys, $identificadores) { return array_merge(array_combine($arrKeys, $arr), $identificadores); }, $arrValores));
}
我的意思不是编辑标签,我的意思是该问题属于codereview.stackexchange.com(在我的第一条评论中链接),而不是stackoverflow.com。我应该删除该问题吗?您可以让主持人迁移它,而不是实际删除它。不过我不太确定,因为我自己从来没有做过。好吧,谢谢,我会问他们:)但你能告诉我哪一个最有效吗?它们的性能几乎相同,但第一个更易于阅读,所以我选择它是因为这个原因。
function formatarArray($arrValores, $arrKeys, $identificadores)
{
print_r(array_map(function ($arr) use ($arrKeys, $identificadores) { return array_merge(array_combine($arrKeys, $arr), $identificadores); }, $arrValores));
}