I have three arrays that are synced with the same key and I need to natsort and apply array_values() to array1 while keeping array2 and array3 in sync with the new keys set for array1 by array_values().
I need to sort the first array naturally and have the other arrays' elements moved to new positions so that columns remain related.
Input arrays:
$array1 = ['OA.3', 'OA.8', 'OA.6', 'OA.2'];
$array2 = [4, 1, 5, 3];
$array3 = [3, 1, 5, 0];
Desired result:
$array1 = ['OA.2', 'OA.3', 'OA.6', 'OA.8'];
$array2 = [3, 4, 5, 1];
$array3 = [0, 3, 5, 1];
Is there some way to keep all three of these arrays in sync during the natsort()
and array_values()
sorting of $array1
? The final result of array2 and array3 show the new keys matching the final result of array1's sorting and re-keying.
You can use the keys of array A after the natsort, to sort the array B and C... Example:
<?PHP
function pre($a) { echo '<pre>'; print_r( $a ); echo '</pre>'; }
$a = array(
0 => 'OA.3',
1 => 'OA.8',
2 => 'OA.6',
3 => 'OA.2'
);
$b = array (
0 => '4',
1 => '1',
2 => '5',
3 => '3'
);
$c = array (
0 => 3,
1 => 1,
2 => 5,
3 => 0,
);
pre( $a );
natsort( $a );
pre( $a );
foreach( $a AS $key => $var ) {
$bb[] = $b[ $key ];
$cc[] = $c[ $key ];
}
echo '$bb:<br />';
pre( $bb );
echo '$cc:<br />';
pre( $cc );
?>
You can apply array_values() on array $a, $bb and $cc after the sorting is done.
Note: pre is just to print the array's inbetween and has no other function.