拼接数组以在特定索引处添加项


Splicing an array to add an item at a specific index

$add = array_splice($fileArr1, $addWhere, 1, $addSong);

我一直在做一个项目一段时间,该项目根据表单中的变量将歌曲名称添加到数组中的特定位置。我真的很困惑,如果这有助于解决我的问题,可以提供额外的代码。谢谢。

<form method="post" action="addtlogan9573.php">
<p><label for="addSong">Add what song? </label><input type="text" name="addSong" id="addSong" /></p>
<p><label for="addWhere">Add where? </label><input type="text" name="addWhere" id="addWhere" /></p>

这是我的全部代码。

<?php
$fileName = "tunes.txt"; 
$fileString = file_get_contents($fileName);
$fileArr = explode("|", $fileString); 
$fileArr1 = array_values($fileArr); 
array_unshift($fileArr1, ' '); 
unset($fileArr1[0]);

if (!$_POST) { 
?>
<form method="post" action="addtlogan9573.php">
<p><label for="addSong">Add what song? </label><input type="text" name="addSong" id="addSong" /></p>
<p><label for="addWhere">Add where? </label><input type="text" name="addWhere" id="addWhere" /></p>
<input class="MyButton" type="submit" name="submit">
</form>

<?php
}
else {

    print "<pre>";
$addSong = $_POST['addSong']; 
$addWhere = $_POST['addWhere'];
$add = array_splice($fileArr1, $addWhere, 1, $addSong);
foreach ($add as $key => $val){
print "$key. $val'n";
}
print "</pre>";
$append=implode("|", $fileArr1); 
file_put_contents("backups/".microtime("tunes.txt"), $append); 
include("inc_navigationtlogan9573.php"); 
?>

您可以遍历数组并创建一个新数组:

if ($_POST['formSubmit']) {  
   $newArr = array();
   $addWhere = $_POST['addWhere'];
   $addSong = $_POST['addSong'];
   $cnt = 0;
  foreach($fileArr1 as $file) {
    if ($cnt == $addWhere) {
        $newArr[] = $addSong;
        $newArr[] = $file;
    } else {
        $newArr[] = $file;
    }
    $cnt++;
  }
}

$newArr是最后一组歌曲。您需要确保将以下内容作为提交按钮:

<input type="submit" name="formSubmit" value="Submit" />

这是你的代码,只有它有效。

<?php
  $fileName = "tunes.txt"; 
  $fileString = file_get_contents($fileName);
  $fileArr = explode("|", $fileString); 
  $fileArr1 = array_values($fileArr); 
  array_unshift($fileArr1, ' '); 
  unset($fileArr1[0]);
?>
<form method="post" action="addtlogan9573.php">
  <p><label for="addSong">Add what song? </label><input type="text" name="addSong" id="addSong" /></p>
  <p><label for="addWhere">Add where? </label><input type="text" name="addWhere" id="addWhere" /></p>
  <input class="MyButton" type="submit" name="formSubmit" />
</form>

<?php
  if ($_POST['formSubmit']) {
     $newArr = array();
   $addWhere = $_POST['addWhere'];
   $addSong = $_POST['addSong'];
   $cnt = 0;
  foreach($fileArr1 as $file) {
    if ($cnt == $addWhere) {
        $newArr[] = $addSong;
        $newArr[] = $file;
    } else {
        $newArr[] = $file;
    }
    $cnt++;
  }
}
  $append=implode("|", $fileArr1); 
  file_put_contents("backups/".microtime("tunes.txt"), $append); 
  include("inc_navigationtlogan9573.php"); 
?>

使用这个:

if (!$_POST)

行不通。您需要引用特定的帖子变量名称。您将使用"$newArr"作为正确的歌曲数组。