Home > Software design >  sort by date ascending and move the ones with null, last
sort by date ascending and move the ones with null, last

Time:12-08

I have a dimensional array, and I would like to move the array with expiryDate => null, last

By the way I searched here before and on google. I can't find my answer

I have an array called $topics

$topics = [
   [
     'expiryDate' => null
   ],
   [
     'expiryDate' => "2030-02-02"
   ]
   [
     'expiryDate' => "2020-02-02"
   ]
];

I would like to move down the first one because the expiry date is null.

this is my code :

foreach ($topics as $key => $value) {

    if ($value['expiryDate'] === null) {
        unset($topics[$key]);
        $topics[] = $value;
    }

}

My expected result is :

$topics = [
   [
     'expiryDate' => "2020-02-02"
   ],
[
     'expiryDate' => "2030-02-02"
   ],
   [
     'expiryDate' => null
   ]
];

CodePudding user response:

Let try usort that:

$topics = [
[
     'expiryDate' => null
   ],
   [
     'expiryDate' => "2020-02-02"
   ]
];

usort($topics, 'cmp');

print_r($topics);

function cmp($a, $b)
{
    return strcmp($b["expiryDate"], $a["expiryDate"]);
}

CodePudding user response:

As Mike advised, use usort.

If you want to sort an array ascending and move null values to the end:

$topics = [
  [
    'expiryDate' => null
  ],
  [
    'expiryDate' => "2030-02-02"
  ],
  [
    'expiryDate' => "2020-02-02"
  ]
];

function cmp($a, $b)
{
  if (is_null($a["expiryDate"])) return 1;
  if (is_null($b["expiryDate"])) return -1;

  // otherwise ascending
  return $a["expiryDate"] > $b["expiryDate"];
}

usort($topics, 'cmp');

echo json_encode($topics);

The output is:

[{"expiryDate":"2020-02-02"},{"expiryDate":"2030-02-02"},{"expiryDate":null}] 
  •  Tags:  
  • php
  • Related