2016-01-25 147 views
1

第一$鍵特定值這真是磨我的齒輪:插入在陣列

if(isset($_POST['does_what'])){ 
    $strings = array(); 
    foreach($_POST['does_what'] as $key => $value){ 
     if($value[$key] == 0){ 
      $strings[0] = "This is $value"; 
     } 
     $strings[] = $value; 
    } 
} 

這給了我錯誤:PHP Notice: Uninitialized string offset: 0

我試着插入上的第一個鍵「一些額外的」文本數組。其他鍵應該插入。

+0

當您訪問字符串或$ null值的變量通常出現的錯誤[$鍵]即與數組語法 – pritesh

+0

顯示'$ _POST ['does_what']'價值打印出來 –

+1

你確定'$值[$ key] 「總是存在?也許你只需要檢查'$ value'? –

回答

0

使用array_unshift

if(!empty($_POST['does_what']) && is_array($_POST['does_what'])){ 
    $strings = array(); 
    foreach($_POST['does_what'] as $key => $value){ 
     if($value[$key] == 0){ 
      $text = "This is ".$value 
      $value = array_unshift($strings[$key], $text); 
     } 
     else{ 
      echo "Value is not a Zero"; 
     } 
     $strings[] = $value; 
    } 
} 
else{ 
    echo "Post is empty Or its not an array"; 
} 

array_unshift Example

+0

這很酷,但爲什麼OP的代碼會拋出通知? –

0

我想你想要更多的東西是這樣的:

foreach($_POST as $key => $value){ 
    if (count($strings) == 0) 
     $strings[] = "This is $value"; 
    else 
     $strings[] = $value; 
+1

'$ strings.length'是一個錯誤的語法。 –

+0

感謝@u_mulder! – voam