PHP,用其他数组变量替换数组变量

时间:2013-01-25 04:14:25

标签: php arrays

以下是示例代码:

$array1 = array("Name1", "Name2", "Name3");
$array2 = array("Name2" => "NameX");
foreach($array1 as $val) 
{
    echo $val."<br/>";
}

这将输出: 名1 名称2 NAME3

我该如何输出: 名1 NameX NAME3

Yogesh Suthar 提交了正确答复:

 $array1 = array("Name1", "Name2", "Name3");

$array2 = array("Name2" => "NameX");
foreach($array1 as $val) {
    if (array_key_exists($val, $array2)) {
            echo $array2[$val];
    }
    else {
            echo $val."<br/>";
    }
}

4 个答案:

答案 0 :(得分:3)

将从字面上理解你的问题&amp;使用你拥有的代码。

$array1 = array("Name1", "Name2", "Name3");
$array2 = array("Name2" => "NameX");
foreach($array1 as $val) {
    if (array_key_exists($val, $array2)) {
            echo $array2[$val]."<br/>";
    }
    else {
            echo $val."<br/>";
    }
}

答案 1 :(得分:1)

我认为你正在寻找array_replace()

<?php
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");

$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
?>

它会输出:

Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)

PHP: array_replace

答案 2 :(得分:1)

foreach ($a1 as $v) {
  if (isset($a2[v]) && !empty($a2[$v]))
    echo "{$a2[$val]}<br />";
  else
    echo "$val<br />";
}

答案 3 :(得分:0)

    $array1 = array("Name1", "Name2", "Name3");
enter code here$array2 = array("Name2" => "NameX");

//Loop tthrough replacement array 
foreach($array2 as $key => $word){
    //Loop through all the replacements
    foreach($array1 as $array1key => $item){

        if($item == $key){
        //if match found replace
        $array1[$array1key] = $word;

        }
    }   
}

print_r($array1);