如何分割二维数组以保存到文件中


How to split a two dimensional array to save to a file

我有一个二维数组,我想保存到一个文件中。文件中的每一行都应该是用制表符分隔的项的详细信息。我将在几分钟内向你展示我的意思。不管怎样,我有一个函数将数组分割成字符串并保存到文件中,但它并没有真正工作。它给了我一个数组到字符串的转换错误。好的,这是我的数组:

{
  [0]=> array(8) {
    ["title"]=> string(20) "The Boys in the Boat"
    ["author"]=> string(18) "Daniel James Brown"
    ["isbn"]=> string(10) "067002581X"
    ["hardcover"]=> string(5) "19.99"
    ["hc-quantity"]=> int(2)
    ["softcover"]=> string(5) "16.99"
    ["sc-quantity"]=> string(1) "9"
    ["e-book"]=> string(6) "16.99 "
  }
  [1]=> array(8) {
    ["title"]=> string(33) "Harry Potter and the Cursed Child"
    ["author"]=> string(40) "J. K. Rowling, Jack Thorne, John Tiffany"
    ["isbn"]=> string(10) "1338099133"
    ["hardcover"]=> string(5) "18.95"
    ["hc-quantity"]=> string(2) "25"
    ["softcover"]=> string(5) "17.98"
    ["sc-quantity"]=> string(1) "0"
    ["e-book"]=> string(6) "17.98 "
  }
  [2]=> array(8) {
    ["title"]=> string(10) "Just Mercy"
    ["author"]=> string(15) "Bryan Stevenson"
    ["isbn"]=> string(10) "0812994520"
    ["hardcover"]=> string(5) "17.50"
    ["hc-quantity"]=> string(1) "8"
    ["softcover"]=> string(5) "16.25"
    ["sc-quantity"]=> string(2) "10"
    ["e-book"]=> string(6) "16.25 "
  }
  [3]=> array(8) {
    ["title"]=> string(13) "Me Before You"
    ["author"]=> string(10) "Jojo Moyes"
    ["isbn"]=> string(10) "0670026603"
    ["hardcover"]=> string(5) "18.95"
    ["hc-quantity"]=> string(1) "2"
    ["softcover"]=> string(5) "17.50"
    ["sc-quantity"]=> string(1) "1"
    ["e-book"]=> string(6) "17.25 "
  }
  [4]=> array(8) {
    ["title"]=> string(24) "A Thousand Splendid Suns"
    ["author"]=> string(15) "Khaled Hosseini"
    ["isbn"]=> string(10) "1594489505"
    ["hardcover"]=> string(5) "19.00"
    ["hc-quantity"]=> string(1) "7"
    ["softcover"]=> string(5) "15.50"
    ["sc-quantity"]=> string(1) "4"
    ["e-book"]=> string(6) "14.95 "
  }
  [5]=> &array(8) {
    ["title"]=> string(19) "The Wright Brothers"
    ["author"]=> string(16) "David McCullough"
    ["isbn"]=> string(10) "1476728742"
    ["hardcover"]=> string(5) "21.95"
    ["hc-quantity"]=> string(1) "3"
    ["softcover"]=> string(5) "18.95"
    ["sc-quantity"]=> string(1) "3"
    ["e-book"]=> string(6) "18.95 "
  }
} 

下面是我的函数:

function saveorder($file,$arr){
  @ $fp = fopen($file, 'w');
  flock($fp, LOCK_EX);
  $string = '';
  foreach($arr as $key => $result)
    $string .= "$key: $result 'n";
  if (!$fp) {
    echo "<p>Your order could not be processed at this time.</p>";
  }else{
    fwrite($fp, $string);
    flock($fp, LOCK_UN);
    fclose($fp);
    echo("<p>Order written to $file file.</p>");
  }    
}

如果可以的话,第一行应该是这样的:"船上的男孩't作者'精装书't",类似这样的内容。你能帮帮我吗?

function saveorder($file,$arr)
{
   $text = [];
   foreach($arr as $row) {
       $text[]= implode("'t", $row);
   }
    file_put_contents($file, implode("'n", $text));
}