Here's sample code:
示例代码:
$array1 = array("Name1", "Name2", "Name3");
$array2 = array("Name2" => "NameX");
foreach($array1 as $val)
{
echo $val."<br/>";
}
This would output: Name1 Name2 Name3
这将输出:Name1 Name2 Name3
How can I output this instead: Name1 NameX Name3
如何输出这个:Name1 NameX Name3
Yogesh Suthar submitted the correct reply:
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 个解决方案
#1
3
Will take your question literally & use the code you have.
从字面上回答你的问题并使用你的代码。
$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/>";
}
}
#2
1
I think you are looking for array_replace()
我认为您正在寻找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);
?>
it will output:
它将输出:
Array
(
[0] => grape
[1] => banana
[2] => apple
[3] => raspberry
[4] => cherry
)
PHP:array_replace
#3
1
foreach ($a1 as $v) {
if (isset($a2[v]) && !empty($a2[$v]))
echo "{$a2[$val]}<br />";
else
echo "$val<br />";
}
#4
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);
#1
3
Will take your question literally & use the code you have.
从字面上回答你的问题并使用你的代码。
$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/>";
}
}
#2
1
I think you are looking for array_replace()
我认为您正在寻找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);
?>
it will output:
它将输出:
Array
(
[0] => grape
[1] => banana
[2] => apple
[3] => raspberry
[4] => cherry
)
PHP:array_replace
#3
1
foreach ($a1 as $v) {
if (isset($a2[v]) && !empty($a2[$v]))
echo "{$a2[$val]}<br />";
else
echo "$val<br />";
}
#4
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);