Reputation: 1491
I need to convert
array(
'0' => 'z1',
'1' => 'Z10',
'2' => 'z12',
'3' => 'Z2',
'4' => 'z3',
)
into
array(
'0' => 'z1',
'3' => 'Z2',
'4' => 'z3',
'1' => 'Z10',
'2' => 'z12',
)
Without using asort. My insert method is not inserting anything into my array what am I doing wrong? P.S is there a better way then doing 2 loops? 1 to go through array then another to loop for position to insert at?
P.S I know it's easy with asort()
.
$arr = array(
'0' => 'z1',
'1' => 'Z10',
'2' => 'z12',
'3' => 'Z2',
'4' => 'z3',
);
$new_arr = array();
$temp = array();
foreach ($arr as $key => $value) {
if (empty($new_arr)) {
$new_arr[$key] = $value;
} else {
if (sanitizeValue($new_arr[$key - 1]) > sanitizeValue($value)) {
foreach ($new_arr as $key_p => $value_p) {
if(sanitizeValue($value) < sanitizeValue($value_p)) {
insert($new_arr, $key_p, array($key=>$value));
}
}
} else {
$new_arr[$key] = $value;
}
}
}
function insert($array, $index, $val) {
$temp = array(); // this temp array will hold the value
$size = count($array); //because I am going to use this more than one time
//echo $size; echo $index;
if (!is_int($index) || $index < 0 || $index > $size) {
return -1;
} else {
$temp = array_slice($array, 0, $index);
$temp[] = $val;
return array_merge($temp, array_slice($array, $index, $size));
}
}
function sanitizeValue($str)
{
$str = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
return $str;
}
echo '<pre>';
print_r($new_arr);
echo '</pre>';
Upvotes: 0
Views: 283
Reputation: 24405
Whenever you need to sort an array you should checking the manual page for Sorting Arrays, it's got a great table which helps you identify which sort function to use.
In this case, you want to use uasort()
to sort by value but keep the keys, and use strnatcasecmp()
to sort the values using a "natural" (human style) sorting method, which will allow you to put 10 after 1, 2 and 3 instead of it being added after 1 by default, in a case-insensitive way (which allows the difference between z1 and Z10 etc.
uasort($example, function($a, $b) {
return strnatcasecmp($a, $b);
});
Array
(
[0] => z1
[3] => Z2
[4] => z3
[1] => Z10
[2] => z12
)
Upvotes: 1