Morten Gustafsson Morten Gustafsson - 1 month ago 20
MySQL Question

Make a 3d array

I want to create a Array with multi-dimension arrays from a database. The Database has 3 tables, one for vehicle, one for damages and one for damagesPhotos.

Table vehicle has two columns id and name

Table damages has four columns damagesID, vehicleID, damagesType and damagesDescription.

Table damagesPhotos has three columns damagesPhotoID and damagesID and damagesPhotoUrl

I need to combine thoose three columns into an array, that looks like this:

$vehicle = array(
"id" => "somestring",
"name" => "somestring",
"damages" => array(
"damagesType" => "somestring",
"damagesDescription" => "somestring",
"photoOfDamages" => array(
"damagesPhotoUrl" => "somestring"
)
)
);


My code looks like this, but is not working the right way.

$result = mysql_query( "SELECT * from vehicle v LEFT JOIN damages d ON v.id = d.vehicleID LEFT JOIN damagesPhotos p ON d.damagesID = p.damagesID WHERE d.damagesID = p.damagesID AND v.id = 1") or die(mysql_error());

$rowsResult = array();

while ($r = mysql_fetch_assoc($result))
{
$rowsResult [] = $r;
}

mysql_free_result($result);

echo json_encode($rowsResult);
...

Answer
$vehicle = array(
    "id" => "somestring",
    "name" => "somestring",
    "damages" => array(
        "type" => "somestring",
        "location" => "somestring",
        "photo" => array(
            "imageurl" => "somestring"
        )
    )
);

For multiple vehicles, it might look more like this:

$vehicles = array(
    0 => array(  // you can omit the numeric index, I'm just using it for clarity
        "id" => "somestring",
        "name" => "somestring",
        "damages" => array(
            "type" => "somestring",
            "location" => "somestring",
            "photo" => array(
                "imageurl" => "somestring"
            )
        )
    ),
    1 => array(
        "id" => "somestring",
        "name" => "somestring",
        "damages" => array(
            "type" => "somestring",
            "location" => "somestring",
            "photo" => array(
                "imageurl" => "somestring"
            )
        )
    )
);