如何更改php数组中的值类型并对其排序..可能吗?
我的代码有问题,希望有人能解决。主要目的是根据数组的值对数组进行排序(然后重新索引其数字键) 我得到了这个文件名示例:如何更改php数组中的值类型并对其排序..可能吗?,php,arrays,sorting,Php,Arrays,Sorting,我的代码有问题,希望有人能解决。主要目的是根据数组的值对数组进行排序(然后重新索引其数字键) 我得到了这个文件名示例: $filename = array("index 198.php", "index 192.php", "index 144.php", "index 2.php", "index 1.php", "index 100.php", "index 111.php"); $alloutput = array(); //all of index in array f
$filename = array("index 198.php", "index 192.php", "index 144.php", "index 2.php", "index 1.php", "index 100.php", "index 111.php");
$alloutput = array(); //all of index in array
foreach ($filename as $name) {
preg_match('#(\d+)#', $name, $output); // take only the numerical from file name
array_shift($output); // cleaned. the last code create duplicate numerical in $output,
if (is_array($output)) {
$alloutput = array_merge($alloutput, $output);
}
}
//try to check the type of every value in array
foreach ($alloutput as $output) {
if (is_array($output)) {
echo "array true </br>";
} elseif (is_int($output)) {
echo "integer true </br>";
} elseif (is_string($output)) { //the numerical taken from filename always resuld "string".
echo "string true </br>";
}
}
$filename=array(“index 198.php”、“index 192.php”、“index 144.php”、“index 2.php”、“index 1.php”、“index 100.php”、“index 111.php”);
$alloutput=array()//数组中的所有索引
foreach($filename作为$name){
preg#u match('#(\d+)#',$name$output);//仅从文件名中获取数字
数组_shift($output);//已清理。最后一个代码在$output中创建重复的数字,
if(is_数组($output)){
$alloutput=array\u merge($alloutput,$output);
}
}
//尝试检查数组中每个值的类型
foreach($alloutput作为$output){
if(is_数组($output)){
回显“数组为真”;
}elseif(is_int($output)){
回显“整数为真”;
}elseif(is_string($output)){//从文件名中获取的数字总是结果为“string”。
回显“字符串为真”;
}
}
此代码的输出将为:
排列
(
[0] => 198
[1] => 192
[2] => 144
[3] => 2
[4] => 1
[5] => 100
[6] => 111
)
我已经测试了数组中的每个输出都是字符串(而不是数字),所以问题是如何将此字符串更改为整数,我可以将其从最低的数字排序为最高的数字
这段代码的主要目的是如何输出从最低到最高排序的数组?使用
使用intval还可以指定基准。如果数字是十进制的,你也可以用
$number = (int) $number_string;
preg\u match
将匹配的部分保留在$outpu[1]
中,因此您可以利用它将字符串
转换为int
,然后将其添加到alloutput
数组中
foreach ($filename as $name) {
preg_match('#(\d+)#', $name, $output);
$alloutput[] = intval($output[1]);
}
我知道这件事。但我希望第一节给出的解决方案。抱歉,如果太多我不理解你的代码,你的循环中有未定义的变量(hasil和hasilku)nicolo,对此我非常抱歉。我会尝试改变它的你再次…哈哈,谢谢,我会设法找到方法来排序它;对不起,我在上面的代码中使用了错误的代码。但我理解你的回答;D@justjoe:要排序,可以使用排序功能。此外,排序之前不必将字符串转换为int。sort函数接受参数sort\u NUMERIC。它将把数组元素视为数字。试试看。
foreach ($filename as $name) {
preg_match('#(\d+)#', $name, $output);
$alloutput[] = intval($output[1]);
}