i have bellow array im trying sort
Array
(
[amendment] => 1
[lcnumber] => A1114564564CT
[31D] => New Note
[27] => 0/0 (Number)(Total)
[31C] =>
[42C] =>
)
Array
(
[amendment] => 2
[lcnumber] => A1114564564CT
[31D] => IN SINGAPORE (120 Days from L/C issue date)
[42C] => 20 Days from B/L Date - Sight
[27] => 2/2 (Number)(Total)
[31C] => Exceeding
)
my expected out put is
Array
(
[amendment] => 1
[lcnumber] => A1114564564CT
[31D] => New Note
[27] => 0/0 (Number)(Total)
[31C] =>
[42C] =>
)
Array
(
[amendment] => 2
[lcnumber] => A1114564564CT
[31D] => IN SINGAPORE (120 Days from L/C issue date)
[27] => 2/2 (Number)(Total)
[31C] => Exceeding
[42C] => 20 Days from B/L Date - Sight
)
means i will have pre defined key order of ('amendment','lcnumber','31D','27','31C','42C')
i tried using usort but i was not able to move forward.
usort($myarray, '');
CodePudding user response:
What you need to do is build a new array with the keys already in the correct order:
$correct_order = ['amendment', 'lcnumber', '31D', '27', '31C', '42C'];
$records = [
[
'amendment' => 1,
'lcnumber' => 'A1114564564CT',
'31D' => 'New Note',
'27' => '0/0 (Number)(Total)',
'31C' => '',
'42C' => ''
],
[
'amendment' => 2,
'lcnumber' => 'A1114564564CT',
'31D' => 'IN SINGAPORE (120 Days from L/C issue date)',
'27' => '2/2 (Number)(Total)',
'42C' => '20 Days from B/L Date - Sight',
'31C' => 'Exceeding'
],
[
'42C' => '0 Days from B/L Date - Sight',
'amendment' => 3,
'31D' => 'IN SINGAPORE (90 Days from L/C issue date)',
'lcnumber' => 'A1114564564CT',
'31C' => 'Exceeding',
'27' => '3/3 (Number)(Total)'
],
];
$corrected = [];
foreach ($records as $record) {
$new = array_fill_keys($correct_order, []);
foreach ($new as $key => &$val) {
$val = $record[$key];
}
$corrected[] = $new;
}
unset($val);
var_dump($corrected);
Results in
array(3) {
[0]=>
array(6) {
["amendment"]=>
int(1)
["lcnumber"]=>
string(13) "A1114564564CT"
["31D"]=>
string(8) "New Note"
[27]=>
string(19) "0/0 (Number)(Total)"
["31C"]=>
string(0) ""
["42C"]=>
string(0) ""
}
[1]=>
array(6) {
["amendment"]=>
int(2)
["lcnumber"]=>
string(13) "A1114564564CT"
["31D"]=>
string(43) "IN SINGAPORE (120 Days from L/C issue date)"
[27]=>
string(19) "2/2 (Number)(Total)"
["31C"]=>
string(9) "Exceeding"
["42C"]=>
string(29) "20 Days from B/L Date - Sight"
}
[2]=>
array(6) {
["amendment"]=>
int(3)
["lcnumber"]=>
string(13) "A1114564564CT"
["31D"]=>
string(42) "IN SINGAPORE (90 Days from L/C issue date)"
[27]=>
string(19) "3/3 (Number)(Total)"
["31C"]=>
string(9) "Exceeding"
["42C"]=>
string(28) "0 Days from B/L Date - Sight"
}
}