如何使用关联数组中的值和键

时间:2015-07-03 09:32:41

标签: php arrays

我有可能有两个数组

array1 = Array
(
    [14] => 0
    [15] => 1
    [16] => 2
    [17] => 3
    [18] => 4
    [19] => 5
    [20] => 6
    [21] => 7
    [22] => 8
    [23] => 9
);

array2 = 
    Array
(
    [0] => 'value'
    [1] => 'value'
    [2] => 'value'
    [3] => 'value'
    [4] => 'value'
    [5] => 'value'
    [6] => 'value'
    [7] => 'value'
    [8] => 'value'
    [9] => 'value'
);

我想成功:

array3 = array( [14]=>'value',[15]=>'value',[16]=>'value',[17]=>'value',[18]=>'value',[19]=>'value',[20]=>'value',[21]=>'value',[22]=>'value',[23]=>'value'));

1 个答案:

答案 0 :(得分:1)

你可以这样做。

<?php 

$array1 = Array
(
    "14" => 0,
    "15" => 1,
    "16" => 2,
    "17" => 3,
    "18" => 4,
    "19" => 5,
    "20" => 6,
    "21" => 7,
    "22" => 8,
    "23" => 9
);

$array2 = 
    Array
(
    "0" => 'value',
    "1" => 'value',
    "2" => 'value',
    "3" => 'value',
    "4" => 'value',
    "5" => 'value',
    "6" => 'value',
    "7" => 'value',
    "8" => 'value',
    "9" => 'value'
);

//Solution #1
foreach($array1 AS $key => $value){
    $array1[$key] = $array2[$value];
}

//solution #2 , thnx to the comments
$array1 = array_combine(array_keys($array1), $array2);

echo "<pre>";
print_r($array1);

?>

输出:

Array
(
    [14] => value
    [15] => value
    [16] => value
    [17] => value
    [18] => value
    [19] => value
    [20] => value
    [21] => value
    [22] => value
    [23] => value
)