Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

php - Return key values from first array whose key is in second array

I have two arrays I want to search from first array by key only which i have in second array and as third array i want to print result:

$colldata=array("bench-press-rod"=>'',"adidas-classic-backpack"=>'93549559913',"adidas-classic-backpack-legend-ink-multicolour"=>'',"puma-suede-classic-regal"=>'93549920361,93549723753');
$colldata2=array(0 => 'bench-press-rod',1 => 'adidas-classic-backpack');

Expected result:

array('bench-press-rod'=>'',"adidas-classic-backpack"=>'93549559913');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this in one line in PHP, using array_flip to swap the keys and values of the second array, and then array_intersect_key to merge the two arrays on matching keys:

$colldata=array("bench-press-rod"=>'',"adidas-classic-backpack"=>'93549559913',"adidas-classic-backpack-legend-ink-multicolour"=>'',"puma-suede-classic-regal"=>'93549920361,93549723753');
$colldata2=array(0 => 'bench-press-rod',1 => 'adidas-classic-backpack');

print_r(array_intersect_key($colldata, array_flip($colldata2)));

Output:

Array
(
    [bench-press-rod] => 
    [adidas-classic-backpack] => 93549559913
)

Demo on 3v4l.org


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...