简体   繁体   English

短代码获取数组,该数组从php中的一个数组获取键并从另一个数组获取值

[英]A short code to get an array that gets keys from one array and values from another in php

Is there any neat way to make an array that its keys comes from the first array and its values come from the second, and discarding any item in the second that does not have any corresponding key in the first? 是否有任何巧妙的方法可以使数组的键来自第一个数组,其值来自第二个数组,并丢弃第二个在第一个数组中没有任何对应键的项? for example if: 例如,如果:

 $keys = array('key1'=>1,'key2'=>2,'key3'=>3);
 $vals = array('key1'=>'val1', 'key4'=>'val4');

the result would be: 结果将是:

 $result=array('key1'=>'val1' , 'key2'=>2 , 'key3'=>3);

Currently, I am using these two lines: 当前,我正在使用这两行:

 $result = array_intersect_key($vals, $keys);
 $result = array_merge($vals, $result);

Is there any cleaner way to do that? 有没有更清洁的方法可以做到这一点?

You're doing it correctly as is. 您按原样正确进行操作。 To reduce a line you could do away with reassigning the $result variable like 为了减少一行,您可以取消重新分配$result变量,例如

 $result = array_merge($vals, array_intersect_key($vals, $keys));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM