2015-10-20 135 views
1

我有一个多维阵列,其中每个条目看起来如下获取键和值:从在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 =“propertyName”。然而,它提供了以下错误:

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

如何从多维一个的内部数组访问信息,但获取在同一时间的关键?

回答

3

有很多不同的方法来处理这个问题。一种选择是使用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。)

+0

我在下面回答了我自己,但是你的printf选项是我学到的新东西,它看起来很棒,我现在要切换到它,它会使事情变得非常干净,谢谢 –

+0

谢谢!为了告诉我关于我的HTML错误 – Jhay

+0

不客气。 –

2

阅读关于variable parsing in strings的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>"; 
2

我总是会写这样的:

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转义引号(“)