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

99封情书 提交于 2019-12-03 12:50:32

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.

Something like:

$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);

I don't know if it the best solution but what I did is

           $previousElement = null;
            foreach ($features as $key => $feature) {
                //check if key is even, otherwise it's 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]);
            }

The best way to do it is with chunking it and using it in 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

just because no one else has pointed it out, this 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];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!