制作一个3d数组

时间:2012-08-30 16:43:47

标签: php mysql arrays database

我想从数据库创建一个包含多维数组的数组。该数据库有3个表,一个用于车辆,一个用于损坏,一个用于损坏照片。

表格工具有两列 ID 名称

表格损失有四列 damageID vehicleID damageType damageDescription

表格损坏照片有三列 damagePhotoID damageID damagePhotoUrl

我需要将thoose三列组合成一个数组,如下所示:

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

我的代码看起来像这样,但工作方式不正确。

$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);
...

2 个答案:

答案 0 :(得分:3)

您可以使用数组执行此操作,但通过使用域对象和数据映射器来填充它们,您可以获得更好的结构。

class Vehicle
{
   private $id;
   private $name;
   private $damages; // collection of Damage objects
}

class Damage
{
  private $id;
  private $type;
  private $photos; // collection of photo objects
}

class Photo
{
  private $id;
  private $imageurl;
} 

您的数据映射器将使用对象上的setter函数在请求时填充数据。

答案 1 :(得分:1)

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

对于多辆车,它看起来可能更像:

$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"
            )
        )
    )
);