重新组织数组:奇数项作为KEY,偶数项作为VALUE [英] Reorganizing an array: odd entries as KEY, even entries as VALUE

查看:259
本文介绍了重新组织数组:奇数项作为KEY,偶数项作为VALUE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试完成为自定义MVC框架创建的URL路由器.我有一个从URL剖析的参数列表,但是问题是它们只有数字键.我想做的就是设置它,以便$ params数组中的第一个值是KEY,然后数组中的第二个值是第一个KEY的VALUE.但是我需要进一步超越它.本质上,我需要将数组中所有奇数键的值都设为新KEY,将偶数键的值都设为新值.

I'm trying to finish up a URL router that I created for my custom MVC framework. I have a list of parameters that I dissected from the URL, but the problem is that they only have numerical keys. What I want to do is set it up so the first value in the $params array will be the KEY and then the second value in the array is the VALUE of the first KEY. But I need to take it beyond that even further. Essentially, I need all odd number key's value in the array to be the new KEY and the even number key's value to be the value.

示例:

这是当前设置的方式:

Array
(
  [0] => greeting
  [1] => hello
  [2] => question
  [3] => how-are-you
  [4] => response
  [5] => im-fine
)

这是(转换后)需求的样子:

This is how it NEEDS to be (after conversion):

Array
(
  [greeting] => hello
  [question] => how-are-you
  [response] => im-fine
)

当我从URL字符串中将其用'/'分隔符展开时,创建这种类型的数组会更容易吗?如果是这样,那么最好的功能是什么?

Would it be easier to create this type of array when I explode the string by the '/' delimiter when I'm taking it out of the URL string? If so, what would be the best function for that?

这可能是一个简单的解决方案,因为我敢肯定这是一个普遍的问题,但是有什么启示吗?

It's probably a simple solution, because I'm sure this is a common issue, but any enlightenment?

推荐答案

也许使用array_splice() 吗?

Maybe use array_splice() for that?

$result = array();

while (count($urls)) {
    list($key,$value) = array_splice($urls, 0, 2);
    $result[$key] = $value;
}

这将从URL列表中提取前两个条目,并将它们用作结果数组的键和值.重复,直到源列表为空.

This will extract the first two entries from the URL list and use those as key and value for the resulting array. Repeats, until the source list is empty.

这篇关于重新组织数组:奇数项作为KEY,偶数项作为VALUE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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