phpmysqlfor-loopmultidimensional-arrayprocedural

How do I create a procedural multi dimensional array with PHP


I'm super new at php, I'm working on a game in Unity c# and I'm trying to send and receive data from a mysql server. I think I'm having a problem with syntax. I basically have a string that's being sent from my c# script that holds multiple ships with their stats. The ships are seperated by zzz which is a string of it's stats separated by space. I'd like to be able to set the stats array within the ships array. This is what I have but it's not working. Thanks!!

$shiparraytobesplit = $_POST["shipinventory"];
$ships =  explode("zzz", $shiparraytobesplit);

for($i = 0; $i<count($ships)-1; $i++)
{

    $tempship[$i] = $ships[$i];
    $tempshipinfo = explode(" ", $tempship);

    for($ii = 0; $ii<count($tempshipinfo[!i])-1; $ii++)
    {
        //$shipinfo[$tempship][] = $info . '_' . $tempshipinfo;
        $shipinfo[$ii] = $tempshipinfo[$ii];    
    }

echo $shipinfo[1];
}

I've tried a few variations but I can't seem to get it to work with this example. I'm probably missing something simple since I'm a total noob to php and kind of new to programming. Thanks again


Solution

  • You have some extraneous subscripts that aren't needed.

    If you have an extra element in the array, it's probably easier to just unset it, then you can loop over the entire array. array_map() is an easy way to produce a new array from an existing array.

    $shiparraytobesplit = $_POST["shipinventory"];
    $ships =  explode("zzz", $shiparraytobesplit);
    unset($ships[count($ships)-1]);
    
    $shipinfo = array_map(function($ship) {
        $tempshipinfo = explode(" ", $ship);
        unset($tempshipinfo[count($tempshipinfo)-1]);
        return $tempshipinfo;
    }, $ships);
    
    print_r($shipinfo);
    

    If you want associative arrays, you can do that in the function.

    $shiparraytobesplit = $_POST["shipinventory"];
    $ships =  explode("zzz", $shiparraytobesplit);
    unset($ships[count($ships)-1]);
    
    $shipinfo = array_map(function($ship) {
        $tempshipinfo = explode(" ", $ship);
        $ship_assoc = [
            "id" => $tempshipinfo[0],
            "name" => $tempshipinfo[1],
            "username" => $tempshipinfo[2],
            "hp" => $tempshipinfo[3]
            ];
        return $ship_assoc;
    }, $ships);
    print_r($shipinfo);