将数组按行PHP存储到txt文件中

时间:2015-04-02 03:46:59

标签: php arrays file

我无法弄清楚如何将整个数组存储到txt文件中。我的代码只存储foreach循环中的最后一行。

 $total_price = 0;
        foreach($_SESSION['shopping_cart'] as $id => $product) {
          $product_id = $product['product_id'];

          $total_price += $products[$product_id]['price'] * $product['quantity'];
          echo "<tr>
            <td style='border-bottom:1px solid #000000;'><a href='./PA3.php?view_product=$id'>" . 
              $products[$product_id]['name'] . "</a></td>
            <td style='border-bottom:1px solid #000000;'>$" . $products[$product_id]['price'] . "</td> 
            <td style='border-bottom:1px solid #000000;'>" . $product['quantity'] . "</td>
            <td style='border-bottom:1px solid #000000;'>$" . ($products[$product_id]['price'] * $product['quantity']) . "</td>
            <td style='border-bottom:1px solid #000000;'>" . $products[$product_id]['picture'] . "</td> 
          </tr>";
        }
      echo "</table>
      <p>Total price: $" . $total_price . "</p>";
      $filename='Order'.date('m-d-Y_hia').'.txt';
            file_put_contents($filename, json_encode($dataArray));  
  }

我认为这是因为我在数组中初始化它,但是当我在它之外初始化它时,我得到一个索引错误。

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

 $filename='Order'.date('m-d-Y_hia').'.txt';

 $fh = fopen($filename, 'w');

  $total_price = 0;
    foreach($_SESSION['shopping_cart'] as $id => $product) {
      $product_id = $product['product_id'];

      $total_price += $products[$product_id]['price'] * $product['quantity'];
      echo "<tr>
        <td style='border-bottom:1px solid #000000;'><a href='./PA3.php?view_product=$id'>" . 
          $products[$product_id]['name'] . "</a></td>
        <td style='border-bottom:1px solid #000000;'>$" . $products[$product_id]['price'] . "</td> 
        <td style='border-bottom:1px solid #000000;'>" . $product['quantity'] . "</td>
        <td style='border-bottom:1px solid #000000;'>$" . ($products[$product_id]['price'] * $product['quantity']) . "</td>
        <td style='border-bottom:1px solid #000000;'>" . $products[$product_id]['picture'] . "</td> 
      </tr>";
    }
  echo "</table>
  <p>Total price: $" . $total_price . "</p>";


  foreach($_SESSION['shopping_cart'] as $id => $product) {

     foreach($product as $k=>$v){

      $stringData = $k . ' - ' . $v . "\n";
       fwrite($fh, $stringData);

     }

  }

        //file_put_contents($filename, json_encode($dataArray));  
}


fclose($fh);