Array reorganization: odd entries like KEY, even entries like VALUE

I am trying to end a URL router created for my user MVC environment. I have a list of parameters that I have broken down from the url, but the problem is that they only have numeric keys. I want to configure it so that the first value in the $ params array is KEY, and then the second value in the array is VALUE of the first KEY. But I need to take it even more. Essentially, I need all the odd number values ​​in the array to be the new KEY value, and the even number value to be the value.

Example:

Here's how it is STRONGLY configured:

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

Here's how it is needed (after conversion):

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

Would it be easier to create this type of array when I blow up the string using the delimiter '/', when I pull it out of the URL string? If so, what would be the best feature to do this?

This is probably a simple solution because I'm sure this is a common problem, but any enlightenment?

+6
source share
5 answers

Maybe use array_splice() for this?

 $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 list of URLs and use them as a key and value for the resulting array. Repeatable until the source list is empty.

+8
source

Sort of:

 $data = array ( 'greeting', 'hello', 'question', 'how-are-you', 'response', 'im-fine', ); $new = array(); for ($i = 0, $lim = sizeof($data); $i < $lim; $i += 2) { $new[$data[$i]] = isset($data[$i + 1]) ? $data[$i + 1] : null; } print_r($new); 
+1
source

I don’t know if this is the best solution, but what I did is

  $previousElement = null; foreach ($features as $key => $feature) { //check if key is even, otherwise it odd if ($key % 2 === 0) { $features[$feature] = $feature; } else { $features[$previousElement] = $feature; } //saving element so I can "remember" it in next loop $previousElement = $feature; unset($features[$key]); } 
0
source

The best way to do this is to smash it and use it on the list.

 $array = array("greeting", "hello", "question", "how-are-you", "response", "im-fine"); $assoc = array(); foreach (array_chunk($array, 2) as $pair) { list($key, $value) = $pair; $assoc[$key] = $value; } var_export($assoc); /* array ( 'greeting' => 'hello', 'question' => 'how-are-you', 'response' => 'im-fine', ) */ 

found here

0
source

simply because no one else pointed it out, it works and is at least as good as the built-in functions for performance:

 $array = array("greeting", "hello", "question", "how-are-you", "response", "im-fine"); $res = array(); for($i=0; $i < count($array); $i+=2){ $res[$array[$i]] = $array[$i+1]; } 
0
source

Source: https://habr.com/ru/post/903743/


All Articles