PHP按第二个数组对array_intersect_key()结果进行排序 [英] PHP sorting array_intersect_key() results by second array

查看:229
本文介绍了PHP按第二个数组对array_intersect_key()结果进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个类中有一个看起来像这样的方法;

I have a method in a class that looks like this;

class SomeClass {
    private $hidden = array(....);

    /**
     * @return array - numeric indexed array in order of $this->hidden.
     * Suitable for use by list(var1, var2, ...)
     */
    public function getAsList($list = array())
    {
       return array_values(array_intersect_key($this->hidden, array_flip($list) );
    }

但这没有用,因为方法的调用者不知道实例变量$ hidden中关联数组中键/元素对的顺序.理想情况下,返回的数组应与$ list中指定的键完全相同的顺序.例如:

But this is not useful, since the caller of the method does not know the order of the key/element pairs in the associative array in instance variable $hidden. Ideally, the returned array would be in the exact same order as the keys specified in $list. For example:

$foo = new SomeClass();
list($foo, $bar, $baz) = $foo->getAsList(array('foo', 'bar', 'baz');

我可以轻松地在循环中编写一些明确的冗长的PHP代码来执行此操作,但是有一些巧妙的方法可以使用各种数组函数,例如array_multisort()可以用最少的代码行吐出来(并希望以编译后的代码速度-如果需要的话,我会对其进行测试).

I can easily write some explicit, verbose PHP code in a loop to do this, but is there some clever way to use the various array functions, e.g. array_multisort() to spit this out in minimal lines of code (and hopefully, at compiled code speed -- I'll test it, if it matters).

从某种意义上说,这是我不知道的答案.在没有显式循环的情况下执行此操作并不重要,但是我很好奇是否可以执行.我花了大约30分钟的时间,但还没有找到解决方法.

In a sense, this is a brain teaser to which I don't yet know the answer. It's not critical I do it without an explicit loop, but I'm curious as to if it can be done. I spent 30 or so minutes on it, and haven't found a solution yet.

推荐答案

也许 array_replace 是困扰您的难题:

public function getAsList($list = array())
{
  $klist = array_flip($list);
  return array_values(array_intersect_key(array_replace($klist, $this->hidden), $klist));
}

示例(演示):

$hidden = [
  'apples' => 19,
  'eggs' => 7,
  'grapes' => 144,
  'mushrooms' => 3,
  'oranges' => 16
];

$list = ['grapes', 'apples', 'eggs', 'oranges'];

$klist = array_flip($list);
print_r(array_values(array_intersect_key(array_replace($klist, $hidden), $klist)));

/*
Array
(
    [0] => 144
    [1] => 19
    [2] => 7
    [3] => 16
)
*/

这篇关于PHP按第二个数组对array_intersect_key()结果进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆