用另一个数组重写数组的键



我想用字符串键重写数组"foo"的数字键。该关系保存在另一个数组"bar"中。

$foo = array(
 1 => 'foo',
 2 => 'bar',
 ...
);
$bar = array(
 1 => 'abc',
 2 => 'xyz',
 ...
);
$result = array(
 'abc' => 'foo',
 'xyz' => 'bar',
 ...
);

实现此结果的最快方法是什么?

使用array_combine函数:

$combined = array_combine($bar, $foo);

print_r($combined);

Array
(
    [abc] => foo
    [xyz] => bar
)

如果两个数组($foo和$bar)中的键/值顺序不同,则 NullPointer 的示例将失败。考虑一下:

$foo = array(
    1 => 'foo',
    2 => 'bar',
);
$bar = array(
    2 => 'xyz',
    1 => 'abc',
);

如果像以前一样运行array_combine($foo, $bar),则输出将是

array(2) {
  ["foo"]=>
  string(3) "xyz"
  ["bar"]=>
  string(3) "abc"
}

但是,这个简单的循环应该有效:

$output = array();
foreach ($bar as $from => $to) {
    $output[$to] = $foo[$from];
}

最新更新