2

这是示例代码:

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

这将输出: Name1 Name2 Name3

我怎样才能输出这个: Name1 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

4 回答 4

3

会从字面上理解您的问题并使用您拥有的代码。

$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/>";
    }
}
于 2013-01-25T04:18:31.880 回答
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:数组替换

于 2013-01-25T04:18:01.707 回答
1
foreach ($a1 as $v) {
  if (isset($a2[v]) && !empty($a2[$v]))
    echo "{$a2[$val]}<br />";
  else
    echo "$val<br />";
}
于 2013-01-25T04:18:04.127 回答
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);
于 2013-01-25T04:34:02.283 回答