从另一个数组替换一个数组的值,使用值替换为键,php

I have two arrays:

$array1 = [29, 1=>'a', 2=>'x',3=>'c', 11];
$array2 = ['a'=>20, 'x'=>21, 'c'=>23];

I want to get an array that looks like:

$array3 = [29, 20, 21, 23, 11];

I know how to do it with a foreach loop, but I was wondering if it was a way to do it as a one liner, or maybe with some sort of anonymus function. Thank you!!

An attempt with a one-liner :

$array1 = [29, 1=>'a', 2=>'x',3=>'c', 11];
$array2 = ['a'=>20, 'x'=>21, 'c'=>23];

$array3 = array_values(array_filter(array_merge($array1,$array2),function($i){return is_int($i);}));

print_r($array3);

// Outputs :
/*
Array
(
    [0] => 29
    [1] => 11
    [2] => 20
    [3] => 21
    [4] => 23
)
*/

You can add them and filter out non-numeric values:

$array3 = array_values(array_filter($array1 + $array2, 'is_numeric'));

If the order is important:

$array3 = array_filter(call_user_func_array(
                       'array_merge', array_map(null, $array1, $array2)), 
                       'is_numeric');

Then array_values if you need to re-index.

In either case, if you want only integers or floats then use is_int or is_float.

array_map work as well the other answer :

$array1 = [29, 1=>'a', 2=>'x',3=>'c', 11];
$array2 = ['a'=>20, 'x'=>21, 'c'=>23];

$array3 = array_map(function($a) use($array2){return is_int($a) ? $a : $array2[$a];}, $array1);

If you don't like to use foreach() you can use array_replace() function. You can learn more about this function in below:

Array_replace($array1 , $array2, $...) in php.net