You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何创建数组而非对象:传递指定目的地的车辆服务费率数组用于onclick函数

How to Generate a Plain PHP Array (Not Object) for Targeted Service Rates

The Problem

I need to compile service rates for the destination International Drive/Sea World into a plain array (not an object) to use in an onclick function. My current code is returning an object instead, and attempts to use array_push() or toArray() haven't fixed the issue:

$international = [];
$i= 0; 
foreach($fleets as $fleet){
    foreach($fleet as $flee){
        foreach($flee->serviceRate as $service){
            if($service->destination == 'International Drive/Sea World'){
                $international = Arr::add($international, $i, $service->rate); 
                $i++;
            }
        }
    }
}

The Solution

Let's break down how to build a proper plain PHP array here:

1. Ditch Arr::add() for native array syntax

Laravel's Arr::add() should return an array, but manually assigning to the array removes any ambiguity and ensures you're working with a plain PHP array. You don't even need to track the index manually—use the shorthand [] to append items:

$international = [];
foreach($fleets as $fleet){
    foreach($fleet as $flee){
        foreach($flee->serviceRate as $service){
            if($service->destination === 'International Drive/Sea World'){
                // Append directly to the array (no index tracking needed!)
                $international[] = $service->rate;
            }
        }
    }
}

This syntax is cleaner and more efficient than array_push() for single items, and guarantees you're building a plain array.

2. Ensure $service->rate isn't an object

If $service->rate itself is an Eloquent model or custom object (instead of a scalar like a float/int), you'll need to extract the actual value. For example:

  • If it's a model with a value property: $international[] = $service->rate->value;
  • If it's a numeric value stored as an object, cast it: $international[] = (float)$service->rate;

3. Verify the result is a plain array

To confirm you're getting a real array (not an object), add a quick debug check:

// Check if it's an array
dd(is_array($international)); // Should return true

// Or inspect the structure
var_dump($international);

Why Your Original Code Failed

While Arr::add() usually returns an array, if your $international variable was accidentally initialized as a Collection (instead of an empty array) somewhere before the loop, or you're on an older Laravel version where Arr::add() behaves differently, it could return a Collection object instead. Using native array assignment avoids this entirely.


内容的提问来源于stack exchange,提问作者Say ma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 21:17:34