2017-08-31 23 views
2

我有一個簡單的數組:回聲數組的鍵:URL和標題

Array 
( 
     [url] => http://localhost/theme/wp-content/uploads/2017/08/img2.png 
     [caption] => title text test 
) 

但我沒有收到關於在foreach權回聲:

<?php foreach ($imgs as $imgurl) { ?>   
    <input name="my_image[url]" type="hidden" value="<?php echo $imgurl[url];?>"/> 
    <input name="my_image[caption]" type="text" value="<?php echo $imgurl[caption];?>"> 

<?php 
}; 
?> 

警告:非法字符串偏移'字幕'在線

+0

不需要'foreach'。只需使用'$ imgs [「url」]'和'$ imgs [「caption」]' –

+0

@SahilGulati僅僅是一個例子,我在真實數組中有更多的數據,有更多的url和標題 – Gislef

+1

你錯過了''''雙引號在'$ imgurl [caption]'中,將其改爲'$ imgurl [「caption」]'並且使用'isset' –

回答

2

你的陣列結構應該是:

array(1) { 
    [0]=> 
    array(2) { 
    ["url"]=> 
    string(58) "http://localhost/theme/wp-content/uploads/2017/08/img2.png" 
    ["caption"]=> 
    string(15) "title text test" 
    } 
} 

,如果你想使用foreach

+0

謝謝,我該如何創建一個這樣的數組?目前這個數組是用'if(isset($ _ POST ['my_image'])){....}自動創建的'' – Gislef

+0

@Gislef可以顯示var_dump的'$ _POST ['my_image']'。 –

+0

var_dump'$ _POST ['my_image']'return:'array(2){[「url」] => string(67)「http:// localhost/theme/wp-content/uploads/2017/08/065.jpg「[」caption「] => string(19)」test other capition「} – Gislef

0

在你的情況爲你的foreach訪問數組應該是二維的。

如果它是具有不同鍵的單個數組,則不需要foreach。你可以直接訪問它。