Reputation: 2683
I have an array with those values:
foreach($dbEntries as $ip){
$ips[] = array(
'location' => $ip->geLocation(),
'description' => $ip->getDescription(),
'note' => $ip->getNote(),
'ipAddress' => $ip->getIpAddress(),
'id' => $ip->getId(),
);
}
Know I would like to sort this array by 'ipAddress' and usually I do it like this (PHP 7):
usort($ips, function($a, $b) {
return $a['ipAddress'] <=> $b['ipAddress'];
});
But that doesn't sort correctly by the IP.
I read about the SORT_NATURAL
flag for array_multisort
but this gives me an error for: $ips = array_multisort($ips['ipAddress'], SORT_NATURAL);
Warning: array_multisort(): Argument #1 is expected to be an array or a sort flag
How would I sort by IP naturally in a multidimensional array?
Upvotes: 0
Views: 594
Reputation: 677
You don't have a key like $ips['ipAddress']
. That's why you are getting that warning.
There's an example in php.net for multi sort that will help your problem.
First you need to collect all ips in one array to sort main one. Here is a sample how you can do it.
<?php
// Obtain a list of columns
$ipList = [];
foreach($dbEntries as $arrayKey => $ip){
$ips[$arrayKey] = [
'location' => $ip->geLocation(),
'description' => $ip->getDescription(),
'note' => $ip->getNote(),
'ipAddress' => $ip->getIpAddress(),
'id' => $ip->getId(),
];
// Collect all ips with same array key
$ipList[$arrayKey] = $ip->getIpAddress();
}
// Sort the data with ipList natural order
// Add $ips as the last parameter, to sort by the common key
array_multisort($ipList, SORT_NATURAL, $ips);
// Now you can use sorted $ips array
print_r($ips);
Upvotes: 2
Reputation: 10148
Try this
foreach ($dbEntries as $key => $row) {
// replace 0 with the index of 'IpAddress'
$entries[$key] = $row[0];
}
array_multisort($entries, SORT_DESC, $dbEntries );
Upvotes: 2