0

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

开始:

$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 中的元素一个年龄值。

4

7 回答 7

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)
}
于 2013-10-17T19:36:33.630 回答
1
$name_map = array();
foreach ($names as $name) {
  $name_map[$name] = isset($ages[$name])?$ages[$name]:null; 
}
于 2013-10-17T19:30:00.187 回答
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;
}
于 2013-10-17T19:32:43.793 回答
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;
    }
}
于 2013-10-17T19:33:06.907 回答
0

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

尝试这个:

$names = array_flip($names);
foreach($names as $key => $value)
{
    $names[$key] = (array_key_exists($key,$ages)) ? $ages[$key] : null;
}
于 2013-10-17T19:35:09.970 回答
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)
}
于 2013-10-17T19:35:58.633 回答
0
array_merge(
   array_combine(
       $names,
       array_fill(0,count($names),NULL)
   ),
   $ages);
于 2013-10-17T19:36:25.457 回答