Convert text file to 2d javascript array using ajax & php

So, I am creating an rpg based browser using Javascript. Initially, my level had one layer and was loaded from a javascript 2d map array. However, I am changing my code to allow support for multiple levels loaded from a file.

I can get the file data without any problems, however I have no idea how to parse the information in suitable arrays.

The contents of my text file are as follows:

LAYER
0, 0, 0, 0, 0
0, 0, 0, 0, 0
0, 0, 0, 0, 0
0, 0, 0, 0, 0
0, 0, 0, 0, 0
LAYER
0, 0, 0, 0, 0
0, 0, 0, 0, 0
0, 0, 0, 0, 0
0, 0, 0, 0, 0
0, 0, 0, 0, 0

My Ajax and PHP to get level;

// JAVASCRIPT
    $.ajax({
            type: 'POST',
            url: 'lib/ajax.php',
            data: {method: 'getLevel'},
            success: function(data){

            },
            error: function(x, h, r){
                console.log(x, h, r);
            }
        })

// PHP FILE 2

public function getLevel(){
   $file = file_get_contents('../levels/level1.txt');
   echo $file;
}

There is an intermediate file that processes all my ajax requests, passing them to a function class.

I can get my level data in order, I just donโ€™t know what to do with it as soon as possible.

, -, , . . - ? php javascript ?

+4
1

LAYER
0, 0, 0, 0, 0
0, 0, 0, 0, 0
0, 0, 0, 0, 0
0, 0, 0, 0, 0
0, 0, 0, 0, 0
LAYER2
0, 0, 0, 0, 0
0, 0, 0, 0, 0
0, 0, 0, 0, 0
0, 0, 0, 0, 0
0, 0, 0, 0, 0

,

function parseLayer($text){
    $layers = array();
    $lines = explode("\n", $text);
    $lastLayer;

    $currArray = array();

    foreach($lines as $line){
        if(strpos($line, ",") === false){
            if(!empty($lastLayer)){
                $layers[$lastLayer] = $currArray;
                $currArray = array();
            }
            $lastLayer = trim($line);
        }else{
            $nodes = explode(",", $line);
            $nodeList = array();
            foreach($nodes as $node){
                $nodeList[] = trim($node);
            }
            $currArray[] = $nodeList;
        }
        $layers[$lastLayer] = $currArray;
    }
    return $layers;
}

, Javascript, JSON php json_encode

@Mike , :

{"LAYER":[
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0]
],
"LAYER2":[
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0]
]
}
+1

Source: https://habr.com/ru/post/1609485/


All Articles