tags:

views:

90

answers:

4

I have an array like the following:

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')
A: 
$array = your array;
$newArray['category_name:'] = $array[1];
$newArray['types:'] = $array[3];
Alexander.Plutov
+2  A: 

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;
Jeriko
$data = $trans; //trans in the arrayfor($i=0, $output = Array(), $max=sizeof($data); $i<$max; $i+=2) { $key = $data[$i]; $value = $data[$i+1]; $output[$key] = $value;}print_r($data);
mayuri
is this correct? i am new to php please help
mayuri
That should work fine. Try `var_dump($output)` and see what it gives you.
Jeriko
it gives me this
mayuri
array(3) { ["category_name:"]=> string(2) "c1" ["types:"]=> string(6) "types:" ["product"]=> string(12) "Basic search" }
mayuri
+1  A: 
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;
}
stereofrog
this gives a range from alphabets, i want in only one array
mayuri
i got it... thanks
mayuri
@mayuri, no, NO, don't use that! it was a joke! use the updated version
stereofrog
+1  A: 

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);
Gumbo
brr.. this is even uglier than mine! +1
stereofrog