在数组中的字符串之间插入空格

时间:2013-01-18 15:29:16

标签: php arrays

我有以下数组:

array('16 HOURS','13.3 HOURS','10.6 HOURS AGO','8 HOURS AGO','5.3 HOURS AGO','2.6 HOURS AGO','CURRENT')

我想在每个字符串之间插入空单元格(''),直到达到所需的长度。我已经尝试了各种循环,对于我等,但总是在CURRENT后面或在16小时之前有白色空间,提前感谢。

2 个答案:

答案 0 :(得分:1)

试试这个。

$array = array('16 HOURS','13.3 HOURS','10.6 HOURS AGO','8 HOURS AGO','5.3 HOURS AGO','2.6 HOURS AGO','CURRENT');

$i = 1;

foreach($array as $val) {
  $tempArray[] = $val;
  if($i < count($array)) {
    $tempArray[] = '';
  }
  $i++;
}

print_r($tempArray);

<强>结果

Array
(
    [0] => 16 HOURS
    [1] => 
    [2] => 13.3 HOURS
    [3] => 
    [4] => 10.6 HOURS AGO
    [5] => 
    [6] => 8 HOURS AGO
    [7] => 
    [8] => 5.3 HOURS AGO
    [9] => 
    [10] => 2.6 HOURS AGO
    [11] => 
    [12] => CURRENT
)

答案 1 :(得分:0)

$myArray = array(
    '16 HOURS',
    '13.3 HOURS',
    '10.6 HOURS AGO',
    '8 HOURS AGO',
    '5.3 HOURS AGO',
    '2.6 HOURS AGO',
    'CURRENT'
);


$newArray = array_combine(
        range(0,12,2),
        $myArray
    ) +
    array_fill_keys(
        range(1,12,2),
        ''
    )
;
ksort($newArray);

var_dump($newArray);