PHP:将一个数组的值设置为另一个数组

时间:2013-10-17 19:24:45

标签: php arrays

我想创建一个新数组,并将其键设置为等于另一个数组的值。

开始:

$names = array("don","james","jennifer","paul");
$ages = array("don" => 25, "paul" => 32);

完成:

$name_age_map = array(
 "don" => 25,
 "james" => null,
 "jennifer" => null,
 "paul" => 32,
);

如何在PHP中完成此操作?这是我迄今为止最好的:

$name_age_map = array();
foreach ($names as $name) {
  $name_age_map[$name] = $name_map[$name]; 
}

理想情况下,我甚至不会创建一个新数组,我只是给$ names中的元素赋予年龄值。

7 个答案:

答案 0 :(得分:4)

只是为了好玩,你可以这样做:

$names = array("don","james","jennifer","paul");
$ages  = array("don" => 25, "paul" => 32);
$names = array_merge(array_fill_keys($names, null), $ages);

var_dump($names);

收率:

array(4) {
  ["don"]=>
  int(25)
  ["james"]=>
  NULL
  ["jennifer"]=>
  NULL
  ["paul"]=>
  int(32)
}

答案 1 :(得分:1)

$name_map = array();
foreach ($names as $name) {
  $name_map[$name] = isset($ages[$name])?$ages[$name]:null; 
}

答案 2 :(得分:0)

问题是$names中的值只是 - 值。为了使它们“平等”成为一个时代,你需要它们成为关键。因为PHP不支持通过引用传递键,这意味着创建一个新数组:

$name_age_map = array();
foreach($names as $name) {
    if(isset($ages[$name])) {
        $name_age_map[$name] = $ages[$name];
    }
    else {
        $name_age_map[] = $name;
    }
}

或者如果你总是希望名字成为键(这可能更有意义):

$name_age_map = array();
foreach($names as $name) {
    $name_age_map[$name] =
            isset($ages[$name]) ? $ages[$name] : null;
}

答案 3 :(得分:0)

$name_age_map = array();

foreach ($names as $name){
    // this can also be replaced with
    // if (array_key_exists($name, $ages)){
    if (in_array($name, array_keys($ages))){
        $name_age_map[$name] = $ages[$name];
    }
    else {
        $name_age_map[$name] = null;
    }
}

答案 4 :(得分:0)

要操作原始数组,您需要将其翻转,然后添加相关的年龄。

试试这个:

$names = array_flip($names);
foreach($names as $key => $value)
{
    $names[$key] = (array_key_exists($key,$ages)) ? $ages[$key] : null;
}

答案 5 :(得分:0)

在比较两个数组中的键时,

array_key_exists()可以帮助您。应用循环并分配找到匹配项的值,否则返回null。这应该适合你。

$names = array("don","james","jennifer","paul");
$ages = array("don" => 25, "paul" => 32);

$merged = array();
foreach($names as $n) {
    if(array_key_exists($n, $ages)) {
        $merged[$n] = $ages[$n];
    } else {
        $merged[$n] = null;
    }
}

var_dump($merged);

//Produces

array(4) {
  ["don"]=>
  int(25)
  ["james"]=>
  NULL
  ["jennifer"]=>
  NULL
  ["paul"]=>
  int(32)
}

答案 6 :(得分:0)

array_merge(
   array_combine(
       $names,
       array_fill(0,count($names),NULL)
   ),
   $ages);