English 中文(简体)
PHP: Can t改为物体
原标题:PHP: Can t read an object
  • 时间:2024-04-26 22:12:29
  •  标签:
  • php

我在尝试将<条码>id> <条码> > $meal 3个小时,但没有成功:

EDIT: 正式法典

use AppModelsRecipe;
use AppModelsMeal;

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 ],
            ]);
        }
}

我愿在此物体内获得补贴。

www.un.org/Depts/DGACM/index_spanish.htm

AppModelsRecipe 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] => * ) )

www.un.org/Depts/DGACM/index_spanish.htm

AppModelsRecipe {#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 [▶]
}

如果I do _r($meal->id)d($meal->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 ];

我做了什么错误?

问题回答

你正在把不同执行途径的结果混为一谈,这就是为什么你的成果没有意义。 一旦您从<代码>Recipe上接下阵列:地点(中间值,美元类别)->get()->toArray();,然后从<代码>Recipe:处(中值,美元类别)->orderBy(热量, des)->first();,要么需要使用相同的数据类型,要么与使用不同的数据加以区别,而模型物体往往没有校准适应器,不加以滥用。

Also method generateCombinations is wild, as it produce array with different dimensions ($n = 1 vs $n = 2), duplicate data too (more items in $items will produce more duplicates), which is not taken into account.





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签