如何将关联数组映射到 html 元素属性?

2022-08-30 18:55:22

我正在构建一个基本的表单构建类来加快我的工作流程,我希望能够采用如下属性数组:

$attributes = array(
   "type"         => "text",
   "id"           => "contact-name",
   "name"         => "contact-name",
   "required"     => true
);

并将其映射到 html 元素的属性:

<input type="text" id="contact-name" name="contact-name" required />

编辑:

实现上述目标的最干净的方法是什么?我确信我可以用一个循环和一些串联来拼凑一些东西,但我感觉printf或类似的东西可以以更优雅的方式做到这一点。


答案 1

我认为这应该这样做:

$result = '<input '.join(' ', array_map(function($key) use ($attributes)
{
   if(is_bool($attributes[$key]))
   {
      return $attributes[$key]?$key:'';
   }
   return $key.'="'.$attributes[$key].'"';
}, array_keys($attributes))).' />';

答案 2
$attr = array(
    'type'     => 'text',
    'id'       => 'contact-name',
    'name'     => 'contact-name',
    'required' => true,
    'value'    => '" <b>html</b> \'test\''
);

echo '<input '. implode(' ', array_map(
    function ($k, $v) { return $k .'="'. htmlspecialchars($v) .'"'; },
    array_keys($attr), $attr
)) .' />';