在数组中的第一个$ key上插入特定值

时间:2016-01-25 18:26:37

标签: php

这真的在磨练我的齿轮:

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

我试图在数组的第一个键上插入“一些额外的”文本。其他键应该插入。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我想你想要更像这样的东西:

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