我正在尝试使用如下语法'漂亮'打印出一个数组:
$outString = "[";
foreach($arr as $key=>$value) {
// Do stuff with the key + value, putting the result in $outString.
$outString .= ", ";
}
$outString .= "]";
Run Code Online (Sandbox Code Playgroud)
然而,这种方法的明显缺点是它会在数组打印结束时,在结束"]之前显示",".有没有一种很好的方法使用$ key => $ value语法来检测你是否在数组中的最后一对,或者我应该使用each()
替换来切换到循环?
Dom*_*ger 12
构建一个数组,然后使用implode
:
$parts = array();
foreach($arr as $key=>$value) {
$parts[] = process($key, $value);
}
$outString = "[". implode(", ", $parts) . "]";
Run Code Online (Sandbox Code Playgroud)