2015-10-20 385 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轉義引號(「)