【发布时间】:2014-05-27 16:46:17
【问题描述】:
我试图在 foreach 循环中使用一个变量,但我得到了奇怪的结果。第一个 foreach 循环工作正常,但通知未定义变量,在第二个版本中没有通知,但它只返回数组中的最后一项。
$formats = array(
'application/x-mpegurl' => 'hls',
'video/webm' => 'webm',
'video/mp4' => 'mp4',
'video/ogg' => 'ogg',
'video/flash' => 'flash',
);
// Works perfectly but there a undefined variable $source
foreach( $formats as $format => $src ){
if ( !empty( $src ) ) {
$source .= '<source type="' . $format . '" src="' . $src . '">';
}
}
echo $source;
// Returns only the last item in the variable but there is no undefined variable
foreach( $formats as $format => $src ){
$source2 = '';
if ( !empty( $src ) ) {
$source2 .= '<source type="' . $format . '" src="' . $src . '">';
}
}
echo $source2;
我用谷歌搜索了没有找到任何解决方案。
【问题讨论】:
标签: php arrays variables loops foreach