PHP newb试图在array1的键中查找array2的值,并在它们匹配的地方对array1的值执行一些操作。我很确定这很容易,但是我对php不是很熟悉。任何帮助都将不胜感激。一直在修补array_search和in_array,但无法让任何东西工作。
希望得到的结果是,在array1的键中找到array2的值时,匹配的键值对的值将除以2。
$array1 = Array (
[shore_anchor] => 0
[inter_anchor] => 0
[offshore_anchor] => 0
[offshore_gear] => 5
[shore_infrastructure] => 0
[inter_infrastructure] => 0
[coastal_vessel] => 5
[offshore_vessel] => 5 );
$array2 = Array ( [0] => infrastructure [1] => anchor );
foreach($array2 as $key1 => $val1){
foreach ($array1 as $key => $value) {
if ($key1 == $key){
echo "$key => $value <br />";
}}}}发布于 2015-06-23 06:58:32
我认为这可能是它,但欢迎评论或效率。
$result = array_flip($array2);
foreach($result as $needle => $val1){
foreach ($array1 as $haystack => $val2) {
if (strpos($haystack, $needle) !== false) {
echo "$haystack => $val2\n";
}
}
}发布于 2015-06-23 07:34:47
一种方法:
<?php
$array1 = Array(
'shore_anchor'=>0,
'inter_anchor'=>0,
'offshore_anchor'=>0,
'offshore_gear'=>5,
'shore_infrastructure'=>0,
'inter_infrastructure'=>0,
'coastal_vessel'=>5,
'offshore_vessel'=>5
);
$array2 = Array(
'0'=>'infrastructure',
'1'=>'anchor'
);
foreach ($array1 as $key=>$value){
$x = explode('_',$key);
if (in_array($x[0],$array2) || in_array($x[1],$array2)){
echo "$key => $value <br />";
}
}
// for PHP 5.6.0 +
$match = '#' . implode('|',$array2) . '#';
$x = array_filter($array1,function ($key) use ($match){
return preg_match($match,$key);
},ARRAY_FILTER_USE_KEY);
foreach ($x as $key=>$value){
echo "$key => $value <br />";
}https://stackoverflow.com/questions/30990944
复制相似问题