将一个数组中的值与另一个数组的键匹配

时间:2015-06-22 22:33:20

标签: php

PHP newb尝试在array2中的密钥中找到array1中的值以及它们匹配的位置对array1的值执行某些操作。很确定这很容易,但我并不熟悉php。任何帮助,将不胜感激。一直在修补array_search,in_array但无法做任何事情。

希望结果是在array2的键中找到array1的值,匹配的键值对的值将被除以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 />";
  }}}}

2 个答案:

答案 0 :(得分:0)

我认为这可能是它,但欢迎提出意见或效率。

$result = array_flip($array2);

foreach($result as $needle => $val1){
    foreach ($array1 as $haystack => $val2) {
        if (strpos($haystack, $needle) !== false) {
            echo "$haystack => $val2\n";
        }
    }
}

答案 1 :(得分:0)

单步:

<?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 />";
}