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



我有一个多维数组,其中每个条目看起来如下:

$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)

如何从多维数组的内部数组访问信息,同时获得键?

有很多不同的方法来处理这个问题。一种选择是使用像这样的复杂字符串语法:

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文档。当你在双引号字符串或here-doc中嵌入数组元素时,有两种方法来写它;简单语法:

"...$array[index]..."

,索引周围没有引号,或者复杂的语法:

"...{array['index']}..."

用花括号括住表达式,以及索引的正常语法。您的错误是因为您使用了第一种语法,但在索引周围加了引号。

所以应该是:

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>"; 

我总是这样写:

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中转义引号(")。

最新更新