0

Let's there's an array that looks like this when printed out:

Array
(
    [0] => B
    [1] => E
    [2] => A
    [3] => D 4
    [4] => D 3
    [5] => D 2
    [6] => D
    [7] => C
    [8] => G
    [9] => F
)

Is there a way to make it look like this:

Array
    (
        [0] => B
        [1] => E
        [2] => A
        [3] => D 
        [4] => D 2
        [5] => D 3
        [6] => D 4
        [7] => C
        [8] => G
        [9] => F
    )

So only sort the numeric values. I've tried doing sort($array); But this sorts it alphabetically

Anyone can help me out?

Thanks in advance!

Frank Lucas
  • 582
  • 2
  • 12
  • 28

3 Answers3

0
$a = array('B', 'E', 'A', 'D 4', 'D 3', 'D 2', 'D', 'C', 'G', 'F');
natsort($a);
print_r($a);

Result

Array
(
    [2] => A
    [0] => B
    [7] => C
    [6] => D
    [5] => D 2
    [4] => D 3
    [3] => D 4
    [1] => E
    [9] => F
    [8] => G
)

more details

Sk_
  • 1,051
  • 8
  • 18
0
<?php 
    $numbers= array("0"=>b,"1"=>e,"2"=>a,"3"=>d4,"4"=>d3,"5"=>d2,"6"=>d3,"7"=>c,"8"=>g,"9"=>f); 
    sort($numbers);
    foreach($numbersas $x => $x_value) {
       echo "Key=" . $x . ", Value=" . $x_value;
       echo "<br>";
    }
?>

Try using krsort()

Hamza Zafeer
  • 2,360
  • 13
  • 30
  • 42
0

This is the solution I came up with:

<?php

$array = array('B', 'E', 'A', 'D 4', 'D 3', 'D 2', 'D', 'C', 'G', 'F');


$map = [];
foreach($array as $token)
{
        $split = explode(' ', $token);

        if( !isset($map[$split[0]]) )
        {
                $map[$split[0]] = []; // initialize letter bucket
        }

        if(count($split) < 2)
        {
                $map[$split[0]][] = 0;
        }
        else
        {
                $map[$split[0]][] = intval($split[1]);
        }
}

$finalArray = [];
foreach($map as $key => $value)
{
        sort($value);
        foreach($value as $num)
        {
                if($num === 0) $finalArray[] = $key;
                else $finalArray[] = $key . ' ' .$num;
        }
}

var_dump($finalArray);

?>

And the output

[root@local]# php test.php
array(10) {
  [0]=>
  string(1) "B"
  [1]=>
  string(1) "E"
  [2]=>
  string(1) "A"
  [3]=>
  string(1) "D"
  [4]=>
  string(3) "D 2"
  [5]=>
  string(3) "D 3"
  [6]=>
  string(3) "D 4"
  [7]=>
  string(1) "C"
  [8]=>
  string(1) "G"
  [9]=>
  string(1) "F"
}
Nadir
  • 1,799
  • 12
  • 20