检查数组是否可以转换为 int 然后转换 laravel
Check if array can be converted to int then convert laravel
我有一个数组集合,我使用 toArray() 将其转换为数组。它将所有项目更改为字符串。我想检查每个可以转换为 integer/decimal 的项目。数组看起来像这样
['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
转换 int
或 float
的方法太多了。这是逻辑:
$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
]
我有一个数组集合,我使用 toArray() 将其转换为数组。它将所有项目更改为字符串。我想检查每个可以转换为 integer/decimal 的项目。数组看起来像这样
['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
转换 int
或 float
的方法太多了。这是逻辑:
$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
]