开发者

Is it possible to create an array from existing array by pairing every two values into key and value?

This is what I want to do.

I have an array.

$arr = array('value1','value2','value3','value4','value5','value6');

Is it possible to pair every two values into something like:

$new_arr = array('value1' => 'value2','value3' => 'value4', 'value5' => 'value6');

In the first array, there are no keys. They are all values. But I want to pair them..in the same order every key => valu开发者_JS百科e (the next to it..just like the example above)

Is something like that possible? I badly need it..


Assuming the array has even number of members you can do:

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

Where $arr is your existing array and $new_array is the new resultant associative array.

Working Ideone link


This might do the trick:

$res = array();

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


Try something like this:

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

Note that the value indexed by the last key is undefined if $arr contains an odd number of items.


Of course it's possible.

function array_pair($arr) {
    $retval = array();
    foreach ($arr as $a) {
        if (isset($key)) {
            $retval[$key] = $a;
            unset($key);
        }
        else {
            $key = $a;
        }
    }
    return $retval;
}

Or you could do:

function array_pair($arr) {
    $retval = array();
    $values = array_values($arr);
    for ($i = 0; $i < count($values); $i += 2)
         $retval[$values[$i]] = $values[$i + 1];
    return $retval;
}


An approach with odd / even indices.

$new_arr = array();
$key = NULL;
for($i=0; $i<count($arr); $i++){
   if($i % 2){ // even indices are values, store it in $new_arr using $key
      $new_arr[ $key ] = $arr[$i];
   }
   else{ // odd indices are keys, store them for future usage
      $key = $arr[$i];
   }
}

Note: the last value will be ignored if the array length is odd.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜