phparraysksort

php ksort trouble on 2 arrays merged


I have an issue with ksort function :

I create to arrays :

foreach ($json2['ticket']['records'] as $item) {
    if ($item['externalId1'] == "325") {
        $subject = $item['subject'];
        $fields1[] = [ //this array must be created dynamic
            $item['insertDate'] => $subject . 'ticket',
        ];

    }
}

$query1204 = 'SELECT * FROM interventions where inter_clientid = "325"';
$result1204 = $db->query($query1204) or die($db->error);
while ($row1204 = $result1204->fetch_array()) {
    $fields2[] = [
        strtotime($row1204['inter_datedebprev']) * 1000 =>
            $row1204['inter_title'] . 'INTER',
    ];
}

And then I ksort a merged version of it

$final = array_merge($fields1,$fields2);
ksort($final);
$fild = json_encode($final);
print_r($fild);

The fact is arrays are sorted separately :

[
{
1559671503000: "Migration téléphonieticket"
 },
{
1559831744000: "Maintenanceticket"
},
{
1561723413000: "Renouvellement de postesticket"
},
{
1561743016000: "Migration vers Office 365ticket"
},
{
1562164271000: "ABO Office 365ticket"
},
{
1564221684000: "sdsfsdfticket"
},
{
1564728016000: "sdfsfticket"
},
{
 1564129800000: "Migration vers Office 365INTER"
},
{
 1564043400000: "Renouvellement de postesINTER"
 },
 {
 1564475400000: "Installation poste Maison AlfortINTER"
 },
 {
 1564644600000: "Installation copieur Maison AlfortINTER"
 }

What is wrong with it

The sorting features should apply on all datas together, not for each block

Thanks!


Solution

  • The function ksort will sort the keys of an array, since your array is multidimensional it is sorting the numeric indexes (i.e. is doing nothing). You will need to compare the keys of each array and for that you can use usort (I'm assuming you just want to order all items by date):

    usort($final, function($a, $b) { return array_keys($a)[0] - array_keys($b)[0]; });