合并两个PHP数组;一个是关键,另一个是价值

时间:2013-05-21 12:21:06

标签: php arrays

我有

数组 A

Array
(
    [0] => 1440:480
    [1] => thumb
    [2] => 240:auto
    [3] => small-thumb
    [4] => big-thumb
    [5] => detail-img
    [6] => tiny-thumb
)

数组 B

Array
(
    [0] => 1440x480
    [1] => 130xauto
    [2] => 240xauto
    [3] => 100xauto
    [4] => 150xauto
    [5] => 650xauto
    [6] => 45xauto
)

如何制作?

数组 C

Array
(
    [1440:480] => 1440x480
    [thumb] => 130xauto
    [240:auto] => 240xauto
    [small-thumb] => 100xauto
    [big-thumb] => 150xauto
    [detail-img] => 650xauto
    [tiny-thumb] => 45xauto
)

5 个答案:

答案 0 :(得分:8)

您只需使用array_combine()

php.net示例:

$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);

输出:

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

答案 1 :(得分:2)

$arr1 = array(0 => '1440:480',
    1 => 'thumb',
    2 => '240:auto',
    3 => 'small-thumb',
    4 => 'big-thumb',
    5 => 'detail-img',
    6 => 'tiny-thumb'
);

$arr2 = array
(
    0 => '1440x480',
    1 => '130xauto',
    2 => '240xauto',
    3 => '100xauto',
    4 => '150xauto',
    5 => '650xauto',
    6 => '45xauto'
);

foreach($arr1 as $key => $val){
    $newArr[$val] = $arr2[$key];
}

print_r($newArr);

答案 2 :(得分:0)

使用array_combine

$c = array_combine($a, $b);

答案 3 :(得分:0)

$a = array(
    "1440:480",
    "thumb",
    "240:auto",
    "small-thumb",
    "big-thumb",
    "detail-img",
    "tiny-thumb"
);

$b = array(
    "1440x480",
    "130xauto",
    "240xauto",
    "100xauto",
    "150xauto",
    "650xauto",
    "45xauto"
);

function merge_arrays($keys, $values) {
   $merged = array();
   for ($i = 0; $i < count($keys); $i++) {
     $merged[$keys[$i]] = $values[$i];
   }
   return $merged;
}

$c = merge_arrays($a, $b);

答案 4 :(得分:0)

不是最复杂的agorythms。猜测两个数组的大小与给定示例中的相同,您可以迭代第一个并使用相同的ID组合它们:

$c = array();
foreach($a as $id => $value){
    $c[$value] = $b[$id];
}