我有一个多维数组,其中每个条目如下所示:
$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/