[英]Check if array can be converted to int then convert laravel
I have an array collection that I converted to array using toArray().我有一个数组集合,我使用 toArray() 将其转换为数组。 Which changes all items to a string.它将所有项目更改为字符串。 I want to check every item that can be converted to an integer/decimal.我想检查每个可以转换为整数/十进制的项目。 The array looks like this数组看起来像这样
['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)
I'm using Laravel/Livewire我正在使用 Laravel/Livewire
you should check first if the item can be converted to integer then convert it if can using ctype_digit , otherwise do nothing:您应该首先检查该项目是否可以转换为整数,然后如果可以使用ctype_digit将其转换,否则什么都不做:
$resultArray= array_map(function ($item){
if(ctype_digit($item))
return floatval($item);
else return $item;
},$array);
return $resultArray;
So many ways to convert int
or float
.转换int
或float
方法有很多。 This is the logic :这是逻辑:
$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);
Result :结果 :
array:6 [
"first_name" => "Jake"
"last_name" => "Doe"
"age" => 13
"address" => "Ivory Street"
"allowance" => 3000
"float?" => 0.6
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.