有序数组到关联数组,奇数作为键

发布于 2024-10-21 08:18:03 字数 775 浏览 4 评论 0原文

非常简单:

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

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

现在我正在使用:

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

我想知道是否有一种方法可以在没有中间变量$arrayOut的情况下做到这一点。我可以编写一个函数,但这是一个单一的用例,我试图保持我的脚本整洁。我只是想知道文档中是否遗漏了一些可以用于此目的的内容。


这些值来自路由路径:

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

它被分解,最终在使用其他组件后,我只剩下 ('key1', 'value1', 'key2', 'value2', ...)< /code>


感谢大家的见解和建议。 长耳朵因其简洁的方法而赢得了这一奖项,当扩展到超过“1行”时,并不是非常神秘(至少我不认为)

但是,也关于长耳朵的建议,也许我对语义上精确的代码和最少的冗长的渴望已经战胜了我,我正在追逐雏菊,试图保持我的变量范围“无污染”,套用我自己的话。

Pretty straightforward:

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

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

Right now I'm using:

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

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

It's exploded, and eventually after using the other components, I'm left with ('key1', 'value1', 'key2', 'value2', ...)


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)

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

鸠魁 2024-10-28 08:18:03

您可以使现有代码稍微更高效(每次迭代删除一个函数调用,在开始时删除一个函数调用:)

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

好吧,(颤抖)这是您的一行:

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

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)));
找个人就嫁了吧 2024-10-28 08:18:03

不需要数组,直接用路径文本即可:

$path = "foo/bar/hello/world";

preg_match_all("#(?J)(?<key>[^/]+)/(?<val>[^/]*)#", $path, $p);
$params = array_combine($p['key'], $p['val']);

print_r($params);
/*
Array
(
    [foo] => bar
    [hello] => world
)
*/

You do not need an array, you can do it directly with the path text:

$path = "foo/bar/hello/world";

preg_match_all("#(?J)(?<key>[^/]+)/(?<val>[^/]*)#", $path, $p);
$params = array_combine($p['key'], $p['val']);

print_r($params);
/*
Array
(
    [foo] => bar
    [hello] => world
)
*/
埋葬我深情 2024-10-28 08:18:03

我不认为你能做得比你现有的更好。但是,当读取输入时,尝试将奇数和偶数元素放入不同的数组中会怎样呢?然后,您可以使用 array_combine 来做一行。

更新array_map不会有帮助,因为它会生成一个具有相同数量元素的数组。您可以使用 array_filter 和 array_combine 进行操作,但同样,这最终不会变得更短。

我真的很喜欢你所拥有的;简短、简单、有效。我只是将其重构为一个函数,比如说 array_interleave_combine 或类似的函数。

更新 2

嗯,您要求的,所以就在这里。如果你问我的话,我会显得太聪明。是一句俏皮话,但我真的不认为它的“纯粹性”足以弥补人们需要了解正在发生的事情所损失的时间:

$result = array_reduce(
    array('foo', 'bar', 'hello', 'world'),
    function($partial, $item) {
        static $nextKey;
        if ($nextKey === null) {
            $nextKey = $item;
        }
        else {
            $partial[$nextKey] = $item;
            $nextKey = null;
        }

        return $partial;
    });

I don't think you can do better than what you have. But what about trying to put the odd and even elements in different arrays when your input is read? You could then use array_combine to make an one-liner.

Update: array_map won't help, as it will produce an array with an equal number of elements. You can do things with array_filter and array_combine, but again, that won't end up being shorter.

I really like what you have; short, simple, does the job. I 'd simply refactor it out into a function, let's say array_interleave_combine or some such.

Update 2:

Well, you asked for it, so here it is. Tries to be too clever if you ask me. Is an one-liner, but I really really don't think the "pureness" of this is enough to pay back the lost time someone would need to understand what's going on:

$result = array_reduce(
    array('foo', 'bar', 'hello', 'world'),
    function($partial, $item) {
        static $nextKey;
        if ($nextKey === null) {
            $nextKey = $item;
        }
        else {
            $partial[$nextKey] = $item;
            $nextKey = null;
        }

        return $partial;
    });
赴月观长安 2024-10-28 08:18:03

该解决方案不需要额外的数组:

$arr = array('foo', 'bar', 'hello', 'world');

for($i = 0, $count = count($arr); $i < $count; $i += 2)
{
  $arr[$arr[$i]] = $arr[$i + 1];
  unset($arr[$i], $arr[$i + 1]);
}

This solution does not need an additional array:

$arr = array('foo', 'bar', 'hello', 'world');

for($i = 0, $count = count($arr); $i < $count; $i += 2)
{
  $arr[$arr[$i]] = $arr[$i + 1];
  unset($arr[$i], $arr[$i + 1]);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文