比较两个数组中的键和值并打印所有值,包括重复值

Compare keys and values from two arrays and print all values including duplicates

我已经有了另一个数组的值,我的问题是如何显示数组中的重复值?

我已经使用 array_intersect_key 尝试过此操作,但不知道如何显示重复项并为其分配值。

$name = "ALLISON";
function toNumber($name) {
    $nameArr = str_split($name);

    $convertArr = array( 
        'A'=>'1', 'J'=>'1', 'S'=>'1',
        'B'=>'2', 'K'=>'2', 'T'=>'2',
        'C'=>'3', 'L'=>'3', 'U'=>'3',
        'D'=>'4', 'M'=>'4', 'V'=>'4',
        'E'=>'5', 'N'=>'5', 'W'=>'5',
        'F'=>'6', 'O'=>'6', 'X'=>'6',
        'G'=>'7', 'P'=>'7', 'Y'=>'7',
        'H'=>'8', 'Q'=>'8', 'Z'=>'8',
        'I'=>'9', 'R'=>'9'
    );          
    $result = array_intersect_key($convertArr, array_flip($nameArr));

    foreach($convertArr as $key => $val) {
        if(array_search($key, $nameArr) === false) {
            unset($convertArr[$key]);
        }
    }   
    print_r($result);           
}
echo toNumber($name);

我得到的输出是这样的:

Array ( [A] => 1 [S] => 1 [L] => 3 [N] => 5 [O] => 6 [I] => 9 )

这是我想要的输出:

Array ( [A] => 1 [S] => 1 [L] => 3 [L] => 3 [N] => 5 [O] => 6 [I] => 9 )

您不能创建具有两次相同键的数组,在您的例子中 'L'。你可以做的是:

$name = 'ALLISON';

function toNumber($name) {

  $nameArr = str_split($name);

  $convertArr = array(
      'A'=>'1', 'J'=>'1', 'S'=>'1',
      'B'=>'2', 'K'=>'2', 'T'=>'2',
      'C'=>'3', 'L'=>'3', 'U'=>'3',
      'D'=>'4', 'M'=>'4', 'V'=>'4',
      'E'=>'5', 'N'=>'5', 'W'=>'5',
      'F'=>'6', 'O'=>'6', 'X'=>'6',
      'G'=>'7', 'P'=>'7', 'Y'=>'7',
      'H'=>'8', 'Q'=>'8', 'Z'=>'8',
      'I'=>'9', 'R'=>'9'
  );

  return array_reduce($nameArr, function ($carry, $item) use ($convertArr) {
    return [ ...$carry, [$item => $convertArr[$item]] ];
  }, []);

}

print_r(toNumber($name));

它将创建一个数组数组:

Array
(
    [0] => Array
        (
            [A] => 1
        )

    [1] => Array
        (
            [L] => 3
        )

    [2] => Array
        (
            [L] => 3
        )

    [3] => Array
        (
            [I] => 9
        )

    [4] => Array
        (
            [S] => 1
        )

    [5] => Array
        (
            [O] => 6
        )

    [6] => Array
        (
            [N] => 5
        )

)