簡體   English   中英

將數據推送到Laravel PHP中的多維數組

[英]push data in to a multidimensional array in laravel php

我想創建一個多維數組以根據日期和類別保存數據,如下所示。 然后,我需要在刀片視圖中顯示此數據?我該怎么做才能做到這一點。

'2012-05-05' => array(
    'suspension' => 52,
    'transmission' => '58'
),
'2012-05-05' => array(
    'suspension' => 44,
    'transmission' => 21

我已經在控制器中完成了以下操作,我希望使用$ reportData變量加載數據。

 public function loadReports(Request $request)
{
    $data = ['2012-05-05','2012-05-06'];
     $salesItems = array();



        $orderItems = OrderItem::with('spare', 'order')->get();

        foreach ($orderItems as $key => $orderItem) {


            if ($orderItem->spare->retailer_id == Auth::user()->id) {
                array_push($salesItems, $orderItem);
            }


        }
        $categories = App\Categories::all();

        foreach ($data as $date) {

            foreach ($categories as $category) {
                $categoryValue = 0;
                foreach ($salesItems as $salesItem) {
                    if ($date == $salesItem->order->orderDate) {
                        $categoryValue += $categoryValue + $salesItem->subTotal;
                    }
                }
                //error appears as illegal offset type
                $reportData[$date][$category]=$categoryValue;



            }
        }


    return View::make('Retailer/reports')->with('categories', $categories)->with('reportData', $reportData);
}

我還沒有測試過它,但是查看您的代碼,看來您正在將對象作為數組索引鍵作為第二級數組索引傳遞:

$reportData[$date][$category] = $categoryValue;
                   ^^^^^^^^^ this is an object

$category轉儲到foreach循環中,然后檢查是否是這種情況: dd($category)

如果您使用的是Eloquent並且您的類別模型具有name屬性,則可能需要將每個類別名稱用作索引值:

$reportData[$date][$category->name] = $categoryValue;

由於您嘗試使用對象作為數組的索引,因此發生了錯誤。

根據laravel文檔( https://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_all ),您在此處調用的all方法為'$ categories = App \\ Category :: all();' 會返回一個雄辯的收藏。

因此,當您遍歷$ categories數組並引用$ category時,您正在引用一個對象。 在PHP中,數組只能用整數或字符串索引。 因此,您需要更改錯誤所在的代碼行

$reportData[$date][$category->someVar] = $categoryValue;

其中someVar是Eloquent模型類別上引用其名稱的變量名稱,例如“ suspension”等。

雖然它不能回答您的問題,但是您可以使用Eloquent引擎使您的生活更輕松:

$orderItems = OrderItem::with('spare', 'order')->get();

foreach ($orderItems as $key => $orderItem) {
    if ($orderItem->spare->retailer_id == Auth::user()->id) {
        array_push($salesItems, $orderItem);
    }
}

可以簡化(並提高效率):

// Store the uid to save the call.
$user_id = Auth::user()->id;

// Apply the condition to the Eloquent query.
$orderItems = OrderItem::with(['spare' => function($query) use ($user_id) {
        return $query->where('retailer_id', '=', $user_id);
}, 'order'])->get();

其他答案是正確的,但是您可能還希望像開始使用它之前一樣初始化$reportData數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM