Reputation: 638
I am trying to make a simple script that will first put an array() into function so I can call on it multiple times to sort. Here is what my array looks like:
// I want this inside of a function so I can call on it:
$a = array(
15 => "C",
12 => "E",
11 => "B",
19 => "P",
10 => "L",
14 => "N",
20 => "A"
);
// This is how I brought it into a function and formatted it:
function original_array($a){
foreach($a as $key => $types) {
print $key . " " . ":" . " " . $types . "<br />";
}
}
I then just have to call original_array() and it prints out fine, but if I sort it once I cant sort it again. It will just print out the first sort:
// Print out array is is:
original_array();
// Then I print out array with sort():
sort($a);
original_array($a);
// But if I try and sort it again with different sort it doesn't work:
ksort($a);
original_array($a);
What am I doing wrong? I am somewhat new to PHP so your help is greatly appreciated.
UPDATE://
This is what I ended up doing. I should have read up on sort function a little more thoroughly. I was unaware that it destroyed the original pointers.
<?php
// Original array:
$a = array(
15 => "C",
12 => "E",
11 => "B",
19 => "P",
10 => "L",
14 => "N",
20 => "A"
);
// Array for sort() function:
$b = $a
function print_format($array){
foreach($array as $key => $types) {
print $key . " " . "=>" . " " . $types . "<br />";
}
}
print "Original";
print_format($a);
print "sort()";
sort($b);
print_format($b);
print "ksort()";
ksort($a);
print_format($a);
print "asort()";
asort($a);
print_format($a);
print "krsort()";
krsort($a);
print_format($a);
print "rsort()";
rsort($b);
print_format($b);
print "arsort()";
arsort($a);
print_format($a);
?>
Upvotes: 1
Views: 1101
Reputation: 1507
You can use reset() function. http://php.net/manual/en/function.reset.php
Upvotes: -1
Reputation: 54757
The normal sort()
function destroys the keys for all values, so when it's sorted, each key is now numeric 0, 1, 2, 3
. Therefore when you use ksort()
, it does nothing because they're already numerically sorted by key.
Try using asort()
to maintain key => value association when sorting by value. Then when you use ksort()
later on, the keys still exist so you can sort in that way.
Upvotes: 4