[英]How can I sort values from an existing array by data type?
I try to determine the data type of each array value from an existing array using foreach() and var_dump().我尝试使用 foreach() 和 var_dump() 从现有数组中确定每个数组值的数据类型。
Let's say I have this array: example:假设我有这个数组:例如:
$arr = ['this','is', 1, 'array', 'for', 1, 'example'];
Now I have to take each value of this field and determine its data type.现在我必须获取该字段的每个值并确定其数据类型。
I try this:我试试这个:
$str = array();
$int = array();
foreach($arr as $k => $val) {
if(var_dump($arr[$k]) == 'string'){
$str[] = $arr[$k];
} else {
$int[] = $arr[$k];
}
}
In other words, I try to sort the values from an existing array by data type and create a new array with only 'string' values and a second new array with only 'int' values.换句话说,我尝试按数据类型对现有数组中的值进行排序,并创建一个仅包含“字符串”值的新数组和第二个仅包含“int”值的新数组。 But it seems that my 'if' condition isn't working properly.
但似乎我的“如果”条件无法正常工作。 How else could I solve this please?
请问我还能怎么解决这个问题? Thank you.
谢谢你。
You need to use gettype
to get the type of a value, not var_dump
:您需要使用
gettype
来获取值的类型,而不是var_dump
:
foreach($arr as $k => $val) {
if(gettype($arr[$k]) == 'string'){
$str[] = $arr[$k];
} else {
$int[] = $arr[$k];
}
}
Output:输出:
Array
(
[0] => this
[1] => is
[2] => array
[3] => for
[4] => example
)
Array
(
[0] => 1
[1] => 1
)
Use gettype
使用
gettype
$data = array('this','is', 1, 'array', 'for', 1, 'example');
foreach ($data as $value) {
echo gettype($value), "\n";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.