Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Okay, so I have an AJAX function that gets a JSON encoded string from a remote PHP file, the response looks like so..

{"zone_id":"1","zone_name":"Test Zone 1","zone_tilemap":"0,0,0,0*0,0,0,0*0,0,0,0*0,0,0,0","zone_objectmap":"0,0,0,0*0,0,0,0*0,0,0,0*0,0,0,0"}

I won't go too far into what this code is about, but the part I need right now is the tilemap, I need to somehow read those numbers into a mutlidimensional JavaScript array so it looks like so...

var someArray = new Array([0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]);

I know that in PHP there is an explode function that can break the string apart by the asterix and then by the commas and put the results into an array, but I'm not great at JavaScript and have no idea how to accomplish this, any ideas?

My AJAX function so far...

function getLocalZoneInformation(){
    $.ajax({
        type: 'POST',
        url: "./inc/backend/game.functions.php?getLocalZoneInformation=" + localCharacterZoneID,
        success: function(response){
            var localZoneInformation = jQuery.parseJSON(response);

            localZoneID = localZoneInformation.zone_id;
            localZoneName = localZoneInformation.zone_name;
            localZoneTileMap = localZoneInformation.zone_tilemap;
            localZoneObjectMap = localZoneInformation.zone_objectmap;
        }
    });
}
share|improve this question
    
Why not add dataType: json and have jQuery parse the response automatically? –  Phil Mar 6 '12 at 3:13
    
I did try this at first but as I said, I'm a beginner and it looked to complicated for my mindset! If you could point me to a tutorial I would be very greatful. –  Brad Bird Mar 6 '12 at 13:00

3 Answers 3

up vote 3 down vote accepted
var tmp = localZoneTileMap.split("*");

var someArray = [];
for (i = 0; i < tmp.length; i++) {
    someArray.push(tmp[i].split(","));
}

If using JavaScript 1.6 or newer, you can use the map() method

var someArray = localZoneTileMap.split("*").map(function(tileMap) {
    return tileMap.split(",");
});
share|improve this answer

Try this:

zones = localZoneName.zone_tilemap.split("*")
out_array = []
for (i in zones) {
    out_array.push(zones[i].split(","))
}

Result will be saved in out_array var.

share|improve this answer
  • Create a typecast (array)
  • loop your object
  • push each elem to the array
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.