开发者

How to convert every two consecutive values of an array into a key/value pair?

I have an array like the f开发者_JAVA百科ollowing:

array('category_name:', 'c1', 'types:', 't1')

I want the alternate values of an array to be the values of an array:

array('category_name:' => 'c1', 'types:' => 't1')


You could try: (untested)

$data = Array("category_name:","c1","types:","t1"); //your data goes here
for($i=0, $output = Array(), $max=sizeof($data); $i<$max; $i+=2) {
  $key = $data[$i];
  $value = $data[$i+1];
  $output[$key] = $value;
}

Alternatively: (untested)

$output = Array();
foreach($data as $key => $value):
  if($key % 2 > 0) { //every second item
    $index = $data[$key-1];
    $output[$index] = $value;
  }
endforeach;


function fold($a) {
    return $a 
        ? array(array_shift($a) => array_shift($a)) 
            + fold($a)
        : array();
}

print_r(fold(range('a','p' )));

~)

upd: a real-life version

function fold2($a) {
    $r = array();
    for($n = 1; $n < count($a); $n += 2)
        $r[$a[$n - 1]] = $a[$n];
    return $r;
}


Here is another yet complex solution:

$keys = array_intersect_key($arr, array_flip(range(0, count($arr)-1, 2)));
$values = array_intersect_key($arr, array_flip(range(1, count($arr)-1, 2)));
$arr = array_combine($keys, $values);


$array = your array;
$newArray['category_name:'] = $array[1];
$newArray['types:'] = $array[3];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜