无法读取对象

问题描述 投票:0回答:1

我已经尝试了3个小时来获取

id
$meal
,但没有成功:

use App\Models\Recipe;
use App\Models\Meal;

class DashboardController extends Controller
{
        // Meal data
            // Function to generate combinations of recipes
            function generateCombinations($items, $n, $start = 0, $result = [], &$results = []) {
                if ($n === 0) {
                    $results[] = $result;
                    return;
                }
            
                for ($i = $start; $i < count($items); $i++) {
                    $result[] = $items[$i];
                    generateCombinations($items, $n - 1, $i + 1, $result, $results);
                    array_pop($result);
                }
            }
            // Function to filter combinations by total calories
            function filterCombinationsByCalories($combinations, $dailyCaloriesMin, $dailyCalories) {
                return array_filter($combinations, function($combination) use ($dailyCaloriesMin, $dailyCalories) {
                    $totalCalories = array_sum(array_column($combination, 'calories'));
                    return $totalCalories >= $dailyCaloriesMin && $totalCalories <= $dailyCalories;
                });
            }
            // Function to get daily meal plan
            function getDailyMealPlan($dailyCalories, $dailyCaloriesMin) {
                $mealCategories = ['breakfast', 'lunch-dinner', 'snacks'];
                $mealPlan = [];
            
                foreach ($mealCategories as $category) {
                    $recipes = Recipe::where('meal', $category)->get()->toArray();
            
                    $combinations = [];
                    generateCombinations($recipes, $category === 'snacks' ? 1 : 2, 0, [], $combinations);
            
                    $filteredCombinations = filterCombinationsByCalories($combinations, $dailyCaloriesMin, $dailyCalories);
            
                    if (empty($filteredCombinations)) {
                        $selectedRecipe = Recipe::where('meal', $category)->orderBy('calories', 'desc')->first();
                        $mealPlan[$category] = $selectedRecipe;
                    } else {
                        $selectedCombination = $filteredCombinations[array_rand($filteredCombinations)];
                        $mealPlan[$category] = $selectedCombination;
                    }
                }
            
                return $mealPlan;
            }

        // Usage
        $dailyCalories = $deficit_tdee_calories; // ex: 1500
        $dailyCaloriesMin = 1300; // ex: 1300
        $mealPlan = getDailyMealPlan($dailyCalories, $dailyCaloriesMin);
        foreach ($mealPlan as $meal) {
            Meal::create([
                'meal_id' => $meal['id'],
            ]);
        }
}

我想获取这个对象内部的id。

print_r($meal)
:

App\Models\Recipe Object ( [connection:protected] => mysql [table:protected] => recipes [primaryKey:protected] => id [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [preventsLazyLoading] => [perPage:protected] => 15 [exists] => 1 [wasRecentlyCreated] => [escapeWhenCastingToString:protected] => [attributes:protected] => Array ( [id] => 29 [recipe] => Creamy Cheese Pancakes [category] => Breakfast Recipes [meal] => breakfast [image] => Creamy_Cheese_Pancakes-Creamy_Cheese_Pancakes.jpg [calories] => 82 [created_at] => [updated_at] => ) [original:protected] => Array ( [id] => 29 [recipe] => Creamy Cheese Pancakes [category] => Breakfast Recipes [meal] => breakfast [image] => Creamy_Cheese_Pancakes-Creamy_Cheese_Pancakes.jpg [calories] => 82 [created_at] => [updated_at] => ) [changes:protected] => Array ( ) [casts:protected] => Array ( ) [classCastCache:protected] => Array ( ) [attributeCastCache:protected] => Array ( ) [dates:protected] => Array ( ) [dateFormat:protected] => [appends:protected] => Array ( ) [dispatchesEvents:protected] => Array ( ) [observables:protected] => Array ( ) [relations:protected] => Array ( ) [touches:protected] => Array ( ) [timestamps] => 1 [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [fillable:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) )

dd($meal)
:

App\Models\Recipe {#1388 ▼
  #connection: "mysql"
  #table: "recipes"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  +preventsLazyLoading: false
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #escapeWhenCastingToString: false
  #attributes: array:8 [▶]
  #original: array:8 [▶]
  #changes: []
  #casts: []
  #classCastCache: []
  #attributeCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [▶]
}

如果我这样做

print_r($meal->id)
print_r($meal['id'])
dd($meal->id)
我会得到 id:

29

但是如果我这样做

$id = $meal['id']
,我就会明白:

Undefined array key "id"

如果我这样做

$id = $meal->id
:

Attempt to read property "id" on array

我不明白为什么。

我尝试过:

$id = $meal[0]['id'];

还尝试过:

$json_decode = json_decode($meal, true);
$id = $json_decode['id'];

我做错了什么?

php
1个回答
0
投票

您正在混合应用程序中不同执行路径的结果,这就是您的结果没有意义的原因。一旦你从

Recipe::where('meal', $category)->get()->toArray();
获取数组,然后从
Recipe::where('meal', $category)->orderBy('calories', 'desc')->first();
获取对象,你要么需要使用相同的数据类型,要么需要区分它们,因为用法不同,通常模型对象没有数组适配器只是为了不滥用它们。

方法

generateCombinations
也很疯狂,因为它产生不同维度的数组(
$n = 1
$n = 2
),重复数据(
$items
中的更多项目将产生更多重复项),这没有被考虑在内。

© www.soinside.com 2019 - 2024. All rights reserved.