How to convert every two consecutive array values ​​to a key / value pair?

I have an array like the following:

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

I want alternative array values ​​to be array values:

array('category_name:' => 'c1', 'types:' => 't1')
+3
source share
4 answers
function fold($a) {
    return $a 
        ? array(array_shift($a) => array_shift($a)) 
            + fold($a)
        : array();
}

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

~)

upd: real version

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

You can 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;
}

Alternative: (unverified)

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

Here is another tricky 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);
+1
source
$array = your array;
$newArray['category_name:'] = $array[1];
$newArray['types:'] = $array[3];
0
source

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


All Articles