更改我的数组,以便将值存储在一起

时间:2018-08-15 16:07:38

标签: php arrays

我有多个可能的用户,这些用户通过AJAX从表单发布到我的PHP脚本中。

在该脚本中,我有以下代码:

parse_str($_POST['users'], $useroutput);

foreach($useroutput as $key => $user){
  // If both fields are filled in:
  if(!empty($user['username']) OR !empty($user['password'])){
    $userstring .= $user['username'].' '.$user['password'].'<br>';
  }else{
    echo 'Empty';
  }
}

但是上面的循环总是向我显示“空”。

虽然这是我打印数组时的样子:

[username] => Array
        (
            [0] => username
            [1] => anotherusername
        )

    [password] => Array
        (
            [0] => password
            [1] => anotherpassword
        )

)

如何更改数组的外观如下:

Array(
    [0] => Array
    (
        [username] = myusername
        [password] = mypassword
    )
    [1] => Array
    (
        [username] = anotherusername
        [password] = anotherpassword
    )
)

我尝试了多种发布数据的方法,但直到现在我还没有找到所需的数组。

这是我将表单数据发布到PHP脚本的方式:

// Add/edit users script
  $( "#companywrap" ).on("click", "#saveuser", function( event ) {
    // Stop normal form behaviour
    event.preventDefault();
    var $form = $("#userform"),
    postBody = $form.serialize(),
    url = $form.attr( "action" );

    var posting = $.post( url, {users: postBody});
    // Show result in a div
    posting.done(function( data ) {
      $( ".resultmessageuser" ).empty().slideDown('fast').append( data );
    });
  });

我的表单标记要求:

<form id="userform" action="includes/userscript.php" method="post" enctype="multipart/form-data">
  <div class="card m-b-20">
    <div class="card-body">
      <div class="form-group fieldGroup">

            <div class="form-group row">
                <label for="example-text-input" class="col-sm-4 col-form-label">Gebruikersnaam</label>
                <div class="col-sm-8">
                    <input class="form-control" name="username[]" value="<?PHP echo $getcompany['username']; ?>" type="text" required>
                </div>
            </div>
            <div class="form-group row">
                <label for="example-text-input" class="col-sm-4 col-form-label">Wachtwoord</label>
                <div class="col-sm-8">
                    <input class="form-control" name="password[]" placeholder="<?PHP echo $editpass; ?>" value='' type="text" required>
                </div>
            </div>
              <div class="input-group-addon">
                  <a href="javascript:void(0)" class="btn btn-success addMore"><span class="glyphicon glyphicon glyphicon-plus" aria-hidden="true"></span> Extra gebruiker</a>
              </div>

      </div>

      <!-- copy of input fields group -->
      <div class="form-group fieldGroupCopy" style="display: none;">

            <div class="form-group row">
                <label for="example-text-input" class="col-sm-4 col-form-label">Gebruikersnaam</label>
                <div class="col-sm-8">
                    <input class="form-control" name="username[]" value="" type="text" id="example-text-input">
                </div>
            </div>
            <div class="form-group row">
                <label for="example-text-input" class="col-sm-4 col-form-label">Wachtwoord</label>
                <div class="col-sm-8">
                    <input class="form-control" name="password[]" placeholder="<?PHP echo $editpass; ?>" value='' type="text" id="example-text-input">
                </div>
            </div>
              <div class="input-group-addon">
                  <a href="javascript:void(0)" class="btn btn-danger remove"><span class="glyphicon glyphicon glyphicon-remove" aria-hidden="true"></span> Verwijder velden</a>
              </div>

      </div>

    </div>
  </div>
</form>

4 个答案:

答案 0 :(得分:3)

我认为您应该首先修改HTML的呈现方式。当前,您的form是以这种方式呈现的:

<form>
    <input type="text" name="username[]">
    <input type="text" name="password[]">

    <input type="text" name="username[]">
    <input type="text" name="password[]">

    <button type="submit">Submit</button>
</form>

将其发送到PHP时,POST请求将如下所示:

[
  "username" => [
    0 => "john"
    1 => "jane"
  ]
  "password" => [
    0 => "pw1"
    1 => "pw2"
  ]
]

但是,如果您将HTML更改为这样的格式:

<form>
    <input type="text" name="credentials[0][username]">
    <input type="text" name="credentials[0][password]">

    <input type="text" name="credentials[1][password]">
    <input type="text" name="credentials[1][password]">

    <button type="submit">Submit</button>
</form>

然后PHP,将看到这样的POST请求:

[
  "credentials" => [
    0 => [
      "username" => "john"
      "password" => "pw1"
    ]
    1 => [
      "username" => "jane"
      "password" => "pw2"
    ]
  ]
]

HTML固定后,您只需要进行一些小的调整:

  1. $.post( url, {users: postBody});更改为$.post( url, postBody);
  2. 现在,您可以使用最初想要的PHP迭代,如下所示:

    foreach($_POST['credentials'] as $credential){
        if(!empty($credential['username']) || !empty($credential['password'])){
            $userstring .= $credential['username'].' '.$credential['password'].'<br>';
        }else{
            echo 'Empty';
        }
    }
    

答案 1 :(得分:1)

您循环不正确。

循环foreach($useroutput as $key => $user){

您得到以下信息:

(
        [0] => username
        [1] => anotherusername
)

这时您没有$user['username']$user[0][1]

如果您这样做:

foreach($useroutput['username'] as $key => $val){
    $users[] = array_combine(['username','password'],array_column($useroutput, $key));
}

Var_dump($users);

您的$ users数组将在该数组中工作,并将用户按预期分组。

答案 2 :(得分:1)

如果两个索引都满足,那么您可以尝试:

$new_array = [];
for($i = 0; $i < count($useroutput); $i++){
  $new_array[] = ['username'=>$useroutput['username'][$i], 'password'=>$useroutput['password'][$i]];
}

$new_array如下:

Array(
    [0] => Array
    (
        [username] = myusername
        [password] = mypassword
    )
    [1] => Array
    (
        [username] = anotherusername
        [password] = anotherpassword
    )
)

答案 3 :(得分:1)

你们都在想这个。输入错误,输出错误。您没有在html中命名键,这会导致枚举数组而不是关联数组。您无需执行复杂的php循环技巧即可解决表单标记布局不正确的问题,只需要更正表单标记以嵌套所需的方式即可。

此:

<input class="form-control" name="username[]" value="<?PHP echo $getcompany['username']; ?>" type="text" required>

需要这样:

<input class="form-control" name="users[]['username']" value="<?PHP echo $getcompany['username']; ?>" type="text" required>

这:

<input class="form-control" name="password[]" placeholder="<?PHP echo $editpass; ?>" value='' type="text" required>

需要这样:

<input class="form-control" name="users[]['password']" placeholder="<?PHP echo $editpass; ?>" value='' type="text" required>

这将在后端生成一个如下所示的数组:

print_r($_POST['users'];
array(
    [0] => array(
        'username' => 'some_username',
        'password' => 'some_password'
    )
);

别聪明。保持简单。