Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

php - Reorganizing an array: odd entries as KEY, even entries as VALUE

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.

Example:

This is how it's CURRENTLY set up:

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
)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Maybe use array_splice() for that?

$result = array();

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...