0

基本上我正在尝试构建一个将查询中的值重复到键中的对象。

   $obj = new stdClass();
   $obj->Product =  (object) array("Name" => "", "Month"=> "", "Price" =>"");
   $obj->Totals = 0.00;

    $r=$shop->get_all_products(0);
   while(mysql_num_rows($r) && $row=mysql_fetch_array($r))
   {
    for ($i=$startMonth; $i<=$endMonth; $i++)
    {
        $thisDate=date("F", mktime(0, 0, 0, $i, 10));

        $r1=$reports->get_sales_by_month($i,$row['product_id']);
        while(mysql_num_rows($r1) && $row1=mysql_fetch_array($r1))
        {
           $totSales=$totSales + $row1['total_price'];
           $obj->Product->Name=$row['product_name'];
           $obj->Product->Month=$thisDate;
           $obj->Product->Price=$row1['total_price'];
           $obj->Totals=$totSales;
        }
    }
   }

当我这样做时var_dump($obj),我只得到查询中的最后一条记录。我希望对象包含所有记录。

4

1 回答 1

2

如果您希望它包含多个值,则 Product 属性需要是一个数组......

试试这个:

$obj = new stdClass();
$obj->Product =  array();
$obj->Totals = 0.00;

$r=$shop->get_all_products(0);
while(mysql_num_rows($r) && $row=mysql_fetch_array($r))
{
 for ($i=$startMonth; $i<=$endMonth; $i++)
 {
     $thisDate=date("F", mktime(0, 0, 0, $i, 10));

     $r1=$reports->get_sales_by_month($i,$row['product_id']);
     while(mysql_num_rows($r1) && $row1=mysql_fetch_array($r1))
     {
        $totSales=$totSales + $row1['total_price'];
        $obj->Product[] = (object)array("Name"=>$row['product_name'], "Month"=>$thisDate, "Price"=>$row1['total_price']);
        $obj->Totals=$totSales;
     }
 }
}
于 2013-06-05T14:53:44.273 回答