PHP电子表格读取CSV

时间:2018-05-01 03:02:33

标签: php csv spreadsheet

我正在尝试使用PHP电子表格库读取CSV文件。

我成功获取了数据但是将逗号分隔到数组中是错误的。

Array
(
    [0] => Array
        (
            [0] => Id,Record,Book,Description,Date,Action
            [1] => 
            [2] => 
        )

    [1] => Array
        (
            [0] => 1306,5466,84,Item,04-05-2018 06
            [1] => 26
            [2] => 28,Auto Show
        )
)

当我看到输出时,它看起来像这样:

Array
(
    [0] => Array
        (
            [0] => Id
            [1] => Record
            [2] => Book
            [3] => Description
            [4] => Date
            [5] => Action
        )

    [1] => Array
        (
            [0] => 1306
            [1] => 5466
            [2] => 84
            [3] => Item
            [4] => 04-05-2018 06:26:28
            [5] => Auto Show
        )
)

代替:

$(document).ready(function() {
  var state = {
  status: "inProgress",
  turn: "human", //can be human or AI
  game: 1,

turnSwitch: function() {
  if (this.turn == "human") {
    return (this.turn = "AI");
  } else if (this.turn == "AI") {
    return (this.turn = "human");
    }
  }
};

//AI will use minimx algorithm to determine best possible move
function player(name, symbol) {
  this.name = name;
  this.symbol = symbol;
}

var human = new player("human", "X");
var AI = new player("AI", "O");

var board = {
    board: [],

    createBoard: function() {
      for (let i = 0; i < 9; i++) {
        this.board.push(i);
      }
      return this.board;
    },

    resetBoard: function() {
      this.board = [];
      createBoard();
    },

    //checks board for terminal state
    terminalTest: function() {
      for (let i = 0; i < 7; i += 3) {
        if (
          this.board[i] == this.board[i + 1] &&
          this.board[i] == this.board[i + 2]
        ) {
          if (typeof this.board[i] !== "number") {
            return this.board[i];
          }
        }
      }

      for (let j = 0; j < 3; j++) {
        if (
          this.board[j] == this.board[j + 3] &&
          this.board[j] == this.board[j + 6]
        ) {
          if (typeof this.board[j] !== "number") {
            return this.board[j];
          }
        }
      }
      if (
        (this.board[0] == this.board[4] && this.board[0] == this.board[8]) ||
        (this.board[2] == this.board[4] && this.board[2] == this.board[6])
      ) {
        if (typeof this.board[4] !== "number") {
          return this.board[4];
        }
      }
    },

    //checks for possible moves
    findEmptyIndicies: function() {
      return this.board.filter(a => typeof a == "number");
    }
  };



function miniMax(boardCurrent, player) {
    //store all possible moves
    var availableMoves = boardCurrent.findEmptyIndicies();
    console.log("available moves length " + availableMoves.length);

    //if terminal state, return score
    var terminalCheck = boardCurrent.terminalTest();

    if (terminalCheck === "X") {
      //console.log(boardCurrent.board + " X wins score: -10")
      return human.symbol == "X" ? { score: -10 } : { score: 10 };
    } else if (terminalCheck === "O") {
      //console.log(boardCurrent.board + " ) wins score: 10")
      return human.symbol == "X" ? { score: 10 } : { score: -10 };
    } else if (availableMoves.length === 0) {
      console.log("availmoves length 0 " + availableMoves.length);
      //console.log(boardCurrent.board + " score: 0")
      return { score: 0 };
    }
    //array to store objects containing index and score through each iteration of available moves
    var movesArray = [];

    for (var i = 0; i < availableMoves.length; i++) {
      //create object to store return score from each index branch
      var move = {};

      move.index = boardCurrent.board[availableMoves[i]];

      boardCurrent.board[availableMoves[i]] = player.symbol;

      //returned score from leaf node if conditionials at top of function are met

      if (player.name == "AI") {
        var miniMaxReturn = miniMax(boardCurrent, human);
        move.score = miniMaxReturn.score;
        console.log("move score " + move.score);
      } else {
        var miniMaxReturn = miniMax(boardCurrent, AI);
        move.score = miniMaxReturn.score;
        console.log("move score " + move.score);
      }

      boardCurrent.board[availableMoves[i]] = move.index;

      movesArray.push(move);
    }
    var bestMove;
    console.log("moves array length " + movesArray.length);
    if (player.name === "AI") {
      let bestScore = -1000;
      for (let i = 0; i < movesArray.length; i++) {
        if (movesArray[i].score > bestScore) {
          bestScore = movesArray[i].score;

          bestMove = i;
        }
      }
    } else if (player.name === "human") {
      let bestScore = 1000;
      for (let i = 0; i < movesArray.length; i++) {
        if (movesArray[i].score < bestScore) {
          bestScore = movesArray[i].score;
          bestMove = i;
        }
      }
    }

    return movesArray[bestMove];
  }



/**function AIMove() {
    console.log("ai move initiated");
    var AIPosition = miniMax(board, AI);
    //var index = AIposition.index;
    //console.log(AIposition);
    //$("#" + index).html(AI.symbol);
  }**/

  $(".cell").click(displayMove);

  function displayMove() {
    if (state.turn == "human") $(this).html(human.symbol);

    board.board[this.id] = human.symbol;

    state.turn = "AI";
    miniMax(board, AI);
    //AIMove();
    console.log("AI move complete");
  }

  $(".cell").click(displayMove);

  //on window load create board
  board.createBoard();

});

提前谢谢。

1 个答案:

答案 0 :(得分:0)

您是否尝试过强制行结尾一致?我之前遇到过这种情况,在解析CSV之前必须添加PHP ini设置:

ini_set('auto_detect_line_endings',TRUE)

把它放在$ reader之前

  

通过评论中的请求进行编辑

这是我用于CSV的类,假设你至少有PHP 5.5:

<?php

use Exception;
use InvalidArgumentException;
use SplFileObject;
use NoRewindIterator;

class LargeFile {

const ERROR_UNABLE = 'ERROR: Unable to open file';
const ERROR_TYPE = 'ERROR: Type must be "ByLength", "ByLine", or "Csv"';

protected $file;
protected $allowed_types = [ 'ByLine', 'ByLength', 'Csv' ];

/**
 * LargeFile constructor.
 *
 * @param $filename
 * @param string $mode
 *
 * @throws Exception
 *
 * Populates $file with new SPL File object instance.
 */
public function __construct($filename, $mode = 'r') {
    if (!file_exists($filename)) {
        $message = __METHOD__ . ' : ' . self::ERROR_UNABLE . PHP_EOL;
        $message .= strip_tags($filename) . PHP_EOL;
        throw new Exception($message);
    }
    $this->file = new SplFileObject($filename, $mode);
}

/**
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with fgets.
 *
 * Suitable for smaller text files like Csvs and / or
 * include line feeds.
 */
protected function fileIteratorByLine() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgets();
        $count++;
    }
    return $count;
}

/**
 * @param $numBytes
 *
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with freads.
 *
 * Suitable for larger binary files.
 */
protected function fileIteratorByLength($numBytes) {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fread($numBytes);
        $count++;
    }
    return $count;
}

protected function fileIteratorCsv() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgetcsv();
        $count++;
    }
    return $count;
}

/**
 * @param string $type
 * @param null $numBytes
 *
 * @return NoRewindIterator
 */
public function getIterator($type = 'ByLine', $numBytes = null) {
    if (!in_array($type, $this->allowed_types)) {
        $message = __METHOD__ . ' : ' . self::ERROR_TYPE . PHP_EOL;
        throw new InvalidArgumentException($message);
    }
    $iterator = 'fileIterator' . $type;
    return new NoRewindIterator($this->$iterator($numBytes));
}
}

你可以像这样使用它:

$largeFile = new LargeFile($file);
// tell it use the CSV iterator
$iterator  = $largeFile->getIterator('Csv');

// start iterator and pull out header row as $rawHeaders
$rawHeaders = $iterator->current();

$headerIterator = new \ArrayIterator;
foreach ($rawHeaders as $header) {
    $headerIterator->append(strtolower("`$header`"));
}

$headers = $headerIterator->getArrayCopy();

// move pointer to the data rows
$iterator->next();

// loop through each row
foreach( $iterator as $row ) {
  // do stuff with each row
  print_r($row);
}