Php 按IP对多维数组排序(自然排序)
我有一个包含以下值的数组:Php 按IP对多维数组排序(自然排序),php,arrays,sorting,Php,Arrays,Sorting,我有一个包含以下值的数组: foreach($dbEntries as $ip){ $ips[] = array( 'location' => $ip->geLocation(), 'description' => $ip->getDescription(), 'note' => $ip->getNote(), 'ipAddress' => $ip->getIpAddress(
foreach($dbEntries as $ip){
$ips[] = array(
'location' => $ip->geLocation(),
'description' => $ip->getDescription(),
'note' => $ip->getNote(),
'ipAddress' => $ip->getIpAddress(),
'id' => $ip->getId(),
);
}
我知道我想按“ipAddress”对这个数组进行排序,通常我是这样做的(PHP7):
usort($ips,function($a,$b){
返回$a['ipAddress']$b['ipAddress'];
});
但这并不能按IP正确排序。
我读到了array\u multisort
的SORT\u NATURAL
标志,但这给了我一个错误:$ips=array\u multisort($ips['ipAddress'],SORT\u NATURAL)代码>
警告:array_multisort():参数#1应为数组或排序标志
如何在多维数组中按IP自然排序?试试这个
foreach ($dbEntries as $key => $row) {
// replace 0 with the index of 'IpAddress'
$entries[$key] = $row[0];
}
array_multisort($entries, SORT_DESC, $dbEntries );
试试这个
foreach ($dbEntries as $key => $row) {
// replace 0 with the index of 'IpAddress'
$entries[$key] = $row[0];
}
array_multisort($entries, SORT_DESC, $dbEntries );
您没有像$ips['ipAddress']
这样的密钥。这就是为什么你会收到这样的警告。
在“多重排序”中有一个示例,可以帮助解决您的问题
首先,您需要在一个数组中收集所有IP,以便对主IP进行排序。这是一个你如何做到这一点的例子
<?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);
您没有像$ips['ipAddress']
这样的密钥。这就是为什么你会收到这样的警告。
在“多重排序”中有一个示例,可以帮助解决您的问题
首先,您需要在一个数组中收集所有IP,以便对主IP进行排序。这是一个你如何做到这一点的例子
<?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);
1:使用ip2long从字符串中生成一个数字,对其排序,使用long2ip将其还原回来。2:当$ips
数组实际上没有这样的索引时,调用$ips['ipAddress']
。1:使用ip2long从字符串中生成数字,对其排序,使用long2ip将其还原。2:当您的$ips
数组实际上没有这样的索引时,您可以调用$ips['ipAddress']
。这太完美了!谢谢你这太完美了!非常感谢。