将键添加到数组和组值

时间:2016-03-17 22:06:31

标签: php arrays

我有简单的数组:

Array(1,3,c,4,a,24,m,4)

我需要将密钥的两个值分组为:

Array
(
    [0] => 1 - 3
    [1] => c - 4
    [2] => a - 24
    [3] => m - 4
)

1 个答案:

答案 0 :(得分:0)

使用foreach循环和array_values函数的简明解决方案:

$arr = [1,3,'c',4,'a',24,'m',4];
$result = [];

foreach ($arr as $k => $v) {
    ($k % 2 == 0)? $result[$k] = $v : $result[$k-1] .= " - $v";
}

var_dump(array_values($result));

// the output:
array (size=4)
  0 => string '1 - 3' (length=5)
  1 => string 'c - 4' (length=5)
  2 => string 'a - 24' (length=6)
  3 => string 'm - 4' (length=5)