我有这个数组:
[0] => Array
(
[tags] => SimpleXMLElement Object
(
[0] => MusicVideos, #20
)
)
[1] => Array
(
[tags] => SimpleXMLElement Object
(
[0] => MusicVideos, #5
)
)
[2] => Array
(
[tags] => SimpleXMLElement Object
(
[0] => #9, MusicVideos
)
)
[3] => Array
(
[tags] => SimpleXMLElement Object
(
[0] => #12, MusicVideos
)
)
现在我想通过[tags]对这个数组进行排序这个PHP怎么做? 使用在线工具[标签]用户在我的网站上订购我希望“#1”,“#2”
但我还有一个比[“#1”和“类别”
更多的[标签] [Tags] => #1
[Tags] => MusicVideos, #2
[Tags] => #3
可能是这样的命令吗?
我尝试使用此功能:
function msort($array, $key, $sort_flags = SORT_NUMERIC) {
if (is_array($array) && count($array) > 0) {
if (!empty($key)) {
$mapping = array();
foreach ($array as $k => $v) {
$sort_key = '';
if (!is_array($key)) {
$sort_key = $v[$key];
} else {
// @TODO This should be fixed, now it will be sorted as string
foreach ($key as $key_key) {
$sort_key .= $v[$key_key];
}
$sort_flags = SORT_STRING;
}
$mapping[$k] = $sort_key;
}
asort($mapping, $sort_flags);
$sorted = array();
foreach ($mapping as $k => $v) {
$sorted[] = $array[$k];
}
return $sorted;
}
}
return $array;
}
但是所有的SORT都会在NAME和下一个NUMBER之后引入EMPTY
[0] => Array
(
[tags] => SimpleXMLElement Object
(
[0] => #5
)
)
[1] => Array
(
[tags] => SimpleXMLElement Object
(
[0] => Commercials, #3
)
)
[2] => Array
(
[tags] => SimpleXMLElement Object
(
[0] => Commercials, #9
)
)
[3] => Array
(
[tags] => SimpleXMLElement Object
(
[0] => MusicVideos, #1
)
)
[4] => Array
(
[tags] => SimpleXMLElement Object
(
[0] => MusicVideos, #10
)
)
我想要这样的东西:
[0] => Array
(
[tags] => SimpleXMLElement Object
(
[0] => MusicVideos, #1
)
)
[1] => Array
(
[tags] => SimpleXMLElement Object
(
[0] => Commercials, #3
)
)
[2] => Array
(
[tags] => SimpleXMLElement Object
(
[0] => #5
)
)
[3] => Array
(
[tags] => SimpleXMLElement Object
(
[0] => Commercials, #9
)
)
[4] => Array
(
[tags] => SimpleXMLElement Object
(
[0] => MusicVideos, #10
)
)
由于
答案 0 :(得分:0)
您应该能够使用usort和适当的可调用来进行排序。
排序功能可以使用任何逻辑来提取排序字段。如果您想按照以#
开头的标记排序,后跟一个数字,您需要在标记字段中找到该子字符串(此处使用正则表达式):
usort($arr, function($a, $b) {
$matches = array();
preg_match('/#(\d+)/', (string) $a['tags'], $matches);
$aTagNo = (int) $matches[1];
preg_match('/#(\d+)/', (string) $b['tags'], $matches);
$bTagNo = (int) $matches[1];
if ($aTagNo < $bTagNo)
return -1;
else if ($aTagNo > $bTagNo)
return 1;
else
return 0;
});