【问题标题】:how to change type of value in an php array and sorting it..is it possible?如何更改php数组中的值类型并对其进行排序..可能吗?
【发布时间】:2010-03-27 09:45:10
【问题描述】:

我的代码有问题,希望有人能够解决。主要目的是根据数组的值对数组进行排序(然后重新索引其数字键)。

我得到了这个文件名样本:

  $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>";
    }   
}

这段代码的输出将是:

大批 ( [0] => 198 [1] => 192 [2] => 144 [3] => 2 [4] => 1 [5] => 100 [6] => 111 )

我已经测试了数组中的每个输出。 都是字符串(不是数字),所以问题是如何把这个字符串改成整数,这样我可以把它从小到大排序? p>

这段代码的主要目的是如何输出从低到高排序的数组?

【问题讨论】:

  • 我看不懂你的代码,你的循环中有未定义的变量(hasil 和 hasilku)
  • nicolo,对此我感到非常抱歉。我会尝试改变它

标签: php arrays sorting


【解决方案1】:

preg_match 会将匹配的部分保留在$outpu[1] 中,因此您可以利用它将string 转换为int,然后将其添加到您的alloutput 数组中。

foreach ($filename as $name) {
    preg_match('#(\d+)#', $name, $output);
    $alloutput[] = intval($output[1]);
}

【讨论】:

  • 又是你……哈哈谢谢,我会设法找到对其进行排序的方法;D
  • 对不起,我在上面的代码中使用了错误的代码。但我理解你的回答;D
  • @justjoe:您可以使用排序功能进行排序。此外,您不必在排序之前将字符串转换为 int。排序函数接受一个参数 SORT_NUMERIC。它将您的数组元素视为数字。试一试。
【解决方案2】:

使用intval

$number_string = '14';
$number = intval('14');

使用 intval 您还可以指定基础。如果是十进制数,也可以使用

$number = (int) $number_string;

【讨论】:

  • 我知道这件事。但我希望在第一个 foreach 中给出解决方案。所以会更直接。对不起,如果它太多了
猜你喜欢
  • 1970-01-01
  • 2022-09-27
  • 2011-10-09
  • 2017-12-13
  • 1970-01-01
  • 2010-10-24
  • 2012-06-09
  • 2021-10-25
  • 2017-07-03
相关资源
最近更新 更多