0

The asort(arrivalTime[]) is not correct. How to correct this when I put all zero on all? The display is:

Array
(
    [4] => 0
    [3] => 0
    [2] => 0
    [1] => 0
    [0] => 0
)

it should be like this and not affecting the index... cause no need to sort when all zero...

Array
(
    [0] => 0
    [1] => 0
    [2] => 0
    [3] => 0
    [4] => 0
)

and when I input another with there is not zero this will the result

Array
(
    [0] => 0
    [2] => 0
    [1] => 0
    [3] => 1
    [4] => 2
)

can anyone have another solution?

EDIT when I used ksort() this is the result... when I input 0, 2, 1 and this is the simple code

<?php
    $test = array(0,2,1);
    ksort($test);
    echo "<pre>";
    print_r($test);
    echo "</pre>";
?>

the output is bug

Array
(
    [0] => 0
    [1] => 2
    [2] => 1
)

all I want is when I put 0,0,0,1 and not changing the key because it's the same...

Array
(
    [0] => 0
    [1] => 0
    [2] => 0
    [3] => 0
)

then another input is 0,2,1,3

Array
(
    [0] => 0
    [2] => 1
    [1] => 2
    [3] => 3
)
8
  • 3
    can you show your code? Commented Apr 22, 2014 at 2:13
  • 1
    after 5 questions you should know how to format code Commented Apr 22, 2014 at 2:16
  • 1
    what action do you like perform with this array? will use foreach loop with this array? or anything else? Commented Apr 22, 2014 at 2:22
  • @samiul i use for loop only... Commented Apr 22, 2014 at 2:28
  • @kennypu my code is just firstComeFirstServe calculator so need to sort the arrival time and when the arrival have all 0 they misplaced... so now I fixed it already thanks to all anyway... Commented Apr 22, 2014 at 2:33

2 Answers 2

1

use ksort() function to sort your arrays by their keys.

Sign up to request clarification or add additional context in comments.

Comments

0

To your question use the ksort(), as the manual.

ksort(arrivalTime[]);

Array
(
    [0] => 0
    [1] => 0
    [2] => 0
    [3] => 0
    [4] => 0
)

Sorts an array by key, maintaining key to data correlations.

$test = array(0,2,1,3);
arsort($test);
echo "<pre>";
print_r($test);
echo "</pre>";

$test = array(0,0,0,1);
ksort($test);
echo "<pre>";
print_r($test);
echo "</pre>";

if($test == array(0,0,0,1)){
    ksort($test);
} else{
    asort($test);
}
echo "<pre>";
print_r($test);
echo "</pre>"; 

9 Comments

but what if i input 4 5 9 2 3 does it sort into 2 3 4 5 9 ?
@JeraldPunx11 Yes. Will ordernar by key, maintaining the correlation between keys and values
@Loïc, excuse me. When I sent the response that came to your answer.
@JeraldPunx11 But Array([0] => 0,[1] => 2,[2] => 1,[3] => 3) is equal to Array([0] => 0,[2] => 1,[1] => 2,[3] => 3). The first is ordered by key but not the latter, but the correlation key and value is the same.
@LucasHenrique but how to do that sort?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.