开发者

how to change type of value in an php array and sorting it..is it possible?

i got problem with my code and hopefully someone able to figure it out. The main purpose is to sort array based on its value (then reindex its numerical key).

i got this sample of filename :

  $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 numerica开发者_运维技巧l taken from filename always resuld "string". 
        echo "string true </br>";
    }   
}

the output of this code will be :

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

i have test every output in array. It's all string (and not numerical), So the question is how to change this string to integer, so i can sort it from the lowest into the highest number ?

the main purpose of this code is how to output array where it had been sort from lowest to highest ?


preg_match will keep the matched part in $outpu[1], so you can make use of that to convert the string to int and then add it to your alloutput array.

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


Use intval

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

With intval you can specify also the basis. If the number is decimal, hower, you can also use

$number = (int) $number_string;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜