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

时间:2015-11-15 21:34:23

标签: php splice

$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"); 

?>

1 个答案:

答案 0 :(得分:0)

您可以迭代数组并创建一个新数组:

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)

没有工作。您需要引用特定的变量名称。您将使用&#39; $ newArr&#39;作为正确的歌曲阵列。

相关问题