2016-01-25 100 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