开发者

Project associative array by key names in PHP

Are there any php function that do this:

$source = array('id1'=>'name', 'id2'=>'name2', 'id3'=>'name3');

$keys = array('id1', 'id3');

$projection = project($source, $keys);

I want:

$projection = array('na开发者_StackOverflow中文版me', 'name3');

I searched the standard array functions for a long time and I could not find anything.


Looks like I should look harder - the trick is to use this function:

$projection = array_intersect_key($source, array_flip($keys))

However, it is ugly because you need to do an array_flip.


Not as such. You could get closer to what you're trying to do using:

$projection = array_values(array_replace(array_flip($keys),$source));

Or:

$projection = array_values(array_intersect_key(array_flip($keys),$source));

However, this will not work if a given item appears twice in the key array.

If you have access to PHP 5.3, you can use a closure:

$projection = array_map(
  function($key) use (&$source) { return $source[$key]; }, $keys
);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜