基于PHP中的另一个数组更新数组

时间:2013-08-23 23:42:42

标签: php arrays merge

我有两个数组

数组$groeperingen包含短代码和全名,数组$groep cointains只包含短代码。

我想要的是$groep中的所有短代码都替换为全名。

数组$groepering如下所示:

Array
(
    [019] => Regio 019a
    [013] => Regio 013
    [011] => Regio alpha
    [AR] => ArmUsers
    [CU] => ComputerUsers
    [GA] => Gamers
    [OP] => Opensource
)

数组$groep如下所示:

Array
(
    [0] => CU
    [1] => GA
    [2] => OP
)

我该怎么做?

2 个答案:

答案 0 :(得分:2)

使用array_map将函数应用于$groep数组的每个元素。

<?php

$groep = Array(
   "CU",
   "GA",
   "OP"
);
$groepering = Array(
   "019" => "Regio 019a",
   "013" => "Regio 013",
   "011" => "Regio alpha",
   "AR" => "ArmUsers",
   "CU" => "ComputerUsers",
   "GA" => "Gamers",                
   "OP" => "Opensource"
);

$result = array_map(function ($x) use ($groepering) {       
   return $groepering[$x];
}, $groep);

print_r($result);

$result的内容是:

Array
(
    [0] => ComputerUsers
    [1] => Gamers
    [2] => Opensource
)

在此处查看:http://phpfiddle.org/main/code/7sv-1kp

答案 1 :(得分:0)

这将创建一个新数组。

$groeperingen = array(
                  '019' => 'Regio 019a',
                  '013' => 'Regio 013',
                  '011' => 'Regio alpha',
                  'AR' => 'ArmUsers',
                  'CU' => 'ComputerUsers',
                  'GA' => 'Gamers',
                  'OP' => 'Opensource'
                );
$groep = array('CA', 'GA', 'OP');

function changeValue($ary, $basedOnAry){
  foreach($ary as $i => $v){
    $a[$i] = $basedOnAry[$v];
  }
  return $a;
}

$newArray = changeValue($groep, $groeperingen);