php - 在 foreach 循环中从多维数组中获取键和值 (PHP/HTML)

标签 php html arrays multidimensional-array foreach

我有一个多维数组,其中每个条目如下所示:

$propertiesMultiArray['propertyName'] = array(
    'formattedName' => 'formattedNameValue', 
    'example' => 'exampleValue', 
    'data' => 'dataValue');

我有一个表单,我想在其中使用 foreach 循环来填充值和输入字段特征,使用外部数组中的键以及存储在内部数组中的不同信息。所有值都将用作字符串。到目前为止,我有

foreach($propertiesMultiArray as $key => $propertyArray){
    echo "<p>$propertyArray['formattedName'] : " .
    "<input type=\"text\" name=\"$key\" size=\"35\" value=\"$propertyArray['data']\">" .
    "<p class=\"example\"> e.g. $propertyArray['example'] </p>" .
    "<br><br></p>"; 
    }

我希望 HTML 片段类似于以下内容:

formattedNameValue : dataValue
e.g. exampleValue

其中 dataValue 在输入文本字段中,$key 用作将输入提交到表单的名称。本质上我想要 $key = "propertyName"。但是,它给出了以下错误:

syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)

如何访问多维内部数组的信息,同时获取key?

最佳答案

有很多不同的方法来处理这个问题。一种选择是使用 complex string syntax像这样:

foreach($propertiesMultiArray as $key => $propertyArray) {
    echo "<p>{$propertyArray['formattedName']} : " .
    "<input type=\"text\" name=\"$key\" size=\"35\" value=\"{$propertyArray['data']}\">" .
    "<p class=\"example\"> e.g. {$propertyArray['example']} </p>" .
    "<br><br></p>"; 
    }

另一种选择是将 HTML 设置为格式字符串,并使用 printf 将其与变量一起输出

$format = '<p>%s : <input type="text" name="%s" size="35" value="%s">
           <p class="example"> e.g. %s </p><br><br></p>';
foreach($propertiesMultiArray as $key => $propertyArray) {
    printf($format, $propertyArray['formattedName'], $key, 
           $propertyArray['data'], $propertyArray['example']);
}

(顺便说一下,我在编写 printf 示例时注意到您的 HTML 中有一个段落包含一个段落。我不认为这是有效的 HTML。)

关于php - 在 foreach 循环中从多维数组中获取键和值 (PHP/HTML),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33246599/

相关文章:

php - 基于所选月份的 CSV 文件输出

php - 查询未返回预期结果

php - 如何将变量传递给@extends blade

c - 通过 for 循环读取字符串时获取随机重复

php - 使用 ffmpeg 时找不到 `ZLIB_1.2.9'

javascript - 在页面加载完成之前显示图像

html - Bootstrap 导航栏 : brand on left - login on right - collapsible menu on center

javascript - 调整大小时缩小/扩大子元素的大小

php - 使用 array_diff 比较多维数组

php - laravel 集合到数组