以特定格式输出数组

时间:2017-10-05 16:12:43

标签: php

我有一个php while循环如下:

$tmp = array();
//loop for category dropdown menu
while($r = $stmt->fetch())        
{
$start_time = $r['consultation_start'];
$end_time = $r['consultation_end'];
$holiday = htmlspecialchars($r['consultation_holidays']);
$tmp[] =sprintf( " $holiday ," );     
}
//concatenate loop strings
foreach($tmp as $output)
{

$holidays =  implode('', $tmp);
$consultholidays = substr_replace($holidays ,"",-1);
}
echo $consultholidays;
$stmt->closeCursor(); 
}

我需要以格式获得输出:

[Sunday], [Wednesday]

我尝试使用:

$tmp[] =sprintf( " [$holiday] ," ); 

但它输出为:

[Sunday,Wednesday] 

如何获得输出格式:

[Sunday], [Wednesday]

对不起,我是php新手并且正在学习。请原谅我的错误。

2 个答案:

答案 0 :(得分:2)

因为我认为如果$ tmp是数组而且这个[Sunday], [Wednesday]数组也是

所以你可以这样做

$tmp[] = [$holiday]; 

但如果这是'[Sunday], [Wednesday]'

之类的字符串

所以试试这个

$tmp[] = $holiday;
echo '['.implode('], [', $tmp).']';

Demo

答案 1 :(得分:2)

尝试以下方法:

$holiday = "Sunday,Wednesday";
$holidays = explode(",",$holiday);

$tmp[] = '['.implode('], [', $holidays).']'; 

var_dump($tmp);

或者这个:

function surround($item)
{
    return "[" . ($item) . "],";
}
$holiday = "Sunday,Wednesday";
$holidays = explode(",",$holiday);
$str = implode(array_map('surround', $holidays));
$tmp[] = rtrim($str,','); 

var_dump($tmp);

第一种方法仅使用内爆来将数组粘合在一起并按], [将它们分开并围绕整个字符串[]

虽然第二个使用array_map围绕单个项目,然后使用implode将其转换为字符串。