有序阵列关联数组,奇数值作为键 [英] Ordered array to associative array, odd values as keys

查看:137
本文介绍了有序阵列关联数组,奇数值作为键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pretty简单:

// turn
array('foo', 'bar', 'hello', 'world');

// into
array('foo' => 'bar', 'hello' => 'world');

现在,我使用:

do{
    $arrayOut[current($arrayIn)] = next($arrayIn);
}while(next($arrayIn));

我不知道是否有办法做到这一点没有变的中介, $ arrayOut 。我可以写一个函数,然而,这是一个一次性使用的情况下,我试图让我的脚本整洁。我只是想知道,如果有什么东西在我的文档错过了将服务于这一目的。

I'm wondering if there's a way to do it without the intermediary variable, $arrayOut. I could write a function, however this is a single use case, and I'm trying to keep my script uncluttered. I'm just wondering if there's something I missed in the docs that would serve this purpose.

的值是从一个路由路径来:

The values are coming from a routing path:

route/to/controller/action/key1/value1/key2/value2

它的爆炸,并最终使用其他组件之后,我留下了('键1','值1','键2','值',...)

感谢您的见解和建议,乡亲。 长耳朵赢得了一个简洁的方法,这时候扩大到超过1号线多了,是不是非常神秘的(我不认为至少)

Thank you folks for the insight and suggestions. Long Ears won this one for the concise approach, which when expanded to more than "1 line", is not terribly cryptic (I don't think at least)

不过,也有关于长耳朵的建议,也许是我的愿望,语义precise code以最小的详细程度已经得到了我的好,我被追的雏菊努力让我的变量的作用域污染物自由,套用自己。

However, also with regard to Long Ears' suggestion, perhaps my desire for semantically precise code with minimal verbosity has gotten the better of me, and I was chasing daisies trying to keep my variable scope "pollutant-free", to paraphrase myself.

推荐答案

您可以让您现有的code稍微更高效(删除每次迭代的一个函数调用,一个开头:)

You can make your existing code slightly more efficient (removes one function call per iteration, for one at the beginning:)

$b = array();
array_unshift($a, false);
while (false !== $key = next($a)) {
    $b[$key] = next($a);
}

好吧,(不寒而栗的),这里是你的单行:

Ok, (shudder) here's your one liner:

$b = call_user_func_array('array_merge', array_map(function($v) { return array($v[0] => $v[1]); }, array_chunk($a, 2)));

这篇关于有序阵列关联数组,奇数值作为键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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