【问题标题】:Convert php array to key=value将php数组转换为key=value
【发布时间】:2014-04-23 22:10:24
【问题描述】:
是否有 php 函数可以将 Array 转换为 html 中的 key=value,如果没有,最好的做法是什么?
输入
$htmlOptions = array('class'=>'container');
...
<div <?php someFunction($htmlOptions); ?> ></div>
输出
<div class="container"></div>
【问题讨论】:
标签:
php
html
arrays
function
yii
【解决方案1】:
这应该没问题:
function printAttributes($array) {
$attrArray = array();
foreach ($array as $name => $value) {
$attrArray[] = $name. '="' . $value . '"';
}
return join(' ', $attrArray);
}
// (...)
$htmlOptions = array('class'=>'container');
然后在HTML中:
<div <?= printAttributes($htmlOptions); ?>></div>
【解决方案2】:
嗯,你可以像这样遍历数组
foreach($array as $key => $value){
echo "This is the key : " . $key . "<br />This is the value : " . $value;
}
这样您将同时获得数组键和值。
【解决方案3】:
使用foreach 更简单
<?php
$htmlOptions = array('class'=>'container');
foreach($htmlOptions as $k=>$v)
{
echo "<div $k='$v'></div>";
}
OUTPUT :
<div class='container'></div>