比较数组中的键并使用比较值创建新数组

I have 2 arrays that I need to compare and then create a new array with the key staying the same, but adding a new array of as value with the two values from the two arrays.

$array1 = (['SE'] => (string) '123', ['DE'] => (string) '456', ['DK'] => (string) '678');
$array2 = (['SE'] => (string) '999', ['DE'] => (string) '888', ['US'] => (string) '777');

So what I want to achieve is to get the value from both arrays where the key is equal to one another. I then need to echo it in a similar fashion;

echo '<table>';
foreach($newCompparedArray as $k => $v){
    echo '<tr>';
    echo '<td>'.$k.'</td><td>'.$v->value1.'</td><td>'.$v->value2.'</td>';
    echo '</tr>';
}
echo '</table>';

Another thing is I need the key to only get the values if the key was present in the initial array (i.e. if a key isn't in array1 but is present in array2, don't add this key or it's values to the new array).

This should give you what you want:

$array1 = array('SE' =>  '123', 'DE' =>  '456', 'DK' =>  '678');
$array2 = array('SE' =>  '999', 'DE' =>  '888', 'US' =>  '777');

$keysInBothArrays = array_intersect(array_keys($array1),array_keys($array2));
$newCompparedArray = array();
foreach ($keysInBothArrays as $key) {
    $newCompparedArray[$key] = array($array1[$key],$array2[$key]);
}
// print_r($newCompparedArray); exit;

echo '<table>';
foreach($newCompparedArray as $k => $v){
    echo '<tr>';
    echo '<td>'.$k.'</td><td>'.$v[0].'</td><td>'.$v[1].'</td>';
    echo '</tr>';
}
echo '</table>';

The trick is to get the keys which are in both arrays first.

Loop the first array, check for the value in the second array and if it exists add both:

foreach($array1 as $k => $v) {
    $newCompparedArray[$k] = isset($array2[$k]) ? array($v, $array2[$k]) : $v;
}

Then your display loop would be:

foreach($newCompparedArray as $k => $v) {
    echo '<td>'.$k.'</td><td>'.$v[0].'</td><td>'.$v[1].'</td>';
}

Obviously in the first loop if you define array('value1'=>$v, 'value2'=>$array2[$k]) then you could use $v['value1] and $v['value2'].

The shorter version:

$newCompparedArray = array_intersect_key(array_merge_recursive($array1, $array2), $array1);

Assuming I understood the output you wanted as

Array(
    [SE] => Array ( [0] => 123, [1] => 999 )
    [DE] => Array ( [0] => 456, [1] => 888 )
    [DK] => Array ( [0] => 678 )
    [US] => Array ( [0] => 777 )
)

I would use this code

$array1 =array ('SE' => '123', 'DE' => '456', 'DK' => '678');
$array2 =array ('SE' => '999', 'DE' => '888', 'US' => '777');

$t =array ();
foreach ( $array1 as $key => $value )
    $t [$key] =array ($value);
foreach ( $array2 as $key => $value ) {
    if ( !isset ($t [$key]) )
        $t [$key] =array ($value);
    else
        $t [$key] [] =$value;
}
//print_r ($t);
foreach ( $t as $key => $value ) {
    echo '<tr>';
    echo "<td>$key</td><td>" . implode ("</td><td>", $value) . '</td>';
    echo "</tr>
";
}