【问题标题】:Check if array can be converted to int then convert laravel [duplicate]检查数组是否可以转换为 int 然后转换 laravel [重复]
【发布时间】:2021-12-15 00:58:33
【问题描述】:

我有一个数组集合,我使用 toArray() 将其转换为数组。它将所有项目更改为字符串。我想检查每个可以转换为整数/小数的项目。数组是这样的

['first_name'] => 'Jake',
['last_name'] => 'Doe',
['age'] => '13', (Change this to an integer/decimal)
['address'] => 'Ivory Street'
['allowance'] => '3000' (Change this to an integer/decimal)

我正在使用 Laravel/Livewire

【问题讨论】:

标签: php laravel eloquent


【解决方案1】:

转换intfloat 的方法有很多。这是逻辑:

$data = collect([
    'first_name' => 'Jake',
    'last_name' => 'Doe',
    'age' => '13',
    'address' => 'Ivory Street',
    'allowance' => '3000',
    'float?' => '0.6'
])
->map(function($item){
    return (is_numeric($item))
        ? ($item == (int) $item) ? (int) $item : (float) $item
        : $item;
})
->toArray();

dd($data);

结果:

array:6 [
  "first_name" => "Jake"
  "last_name" => "Doe"
  "age" => 13
  "address" => "Ivory Street"
  "allowance" => 3000
  "float?" => 0.6
]

【讨论】:

  • 这是正确的,但现在我在映射一个数组时遇到了一个问题,当它的值为 null 时,它会将其更改为 0.00
  • null 值没有问题。你确定吗?
  • 我的不好,它可以工作,但我在刀片文件中显示它时遇到了问题。我也解决了,这就是答案。
猜你喜欢
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
  • 2015-03-14
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2017-12-04
  • 1970-01-01
相关资源
最近更新 更多