我正在跟踪我的产品描述中出现了多少单词,并创建了一个跟踪的多维数组,但我需要将最常找到的关键字排序到最低位。我有这个数组,我希望能够通过“count”键对它进行排序:
Array
(
[KOM1-K182924DA] => Array
(
[count] => 1
[words] => Array
(
[4] => cotton
)
)
[PVH1-U2666001] => Array
(
[count] => 2
[words] => Array
(
[2] => cotton
[5] => briefs
)
)
[GEO2-K2345TF] => Array
(
[count] => 1
[words] => Array
(
[4] => red
)
)
[KOM1-K182871HK] => Array
(
[count] => 3
[words] => Array
(
[4] => cotton
[5] => nylon
[6] => blue
)
)
)
所以结果看起来像这样:
Array
(
[KOM1-K182871HK] => Array
(
[count] => 3
[words] => Array
(
[4] => cotton
[5] => nylon
[6] => blue
)
)
[PVH1-U2666001] => Array
(
[count] => 2
[words] => Array
(
[2] => cotton
[5] => briefs
)
)
[KOM1-K182924DA] => Array
(
[count] => 1
[words] => Array
(
[4] => cotton
)
)
[GEO2-K2345TF] => Array
(
[count] => 1
[words] => Array
(
[4] => red
)
)
)
我该怎么做?我尝试过在stackoverflow上找到的多个解决方案,但它们都没有对我有用。我在这里尝试了解决方案Sort Multi-dimensional Array by Value。我正在使用PHP 5.6,所以我尝试了这个:
usort($myArray, function($a, $b) {
return $a['order'] - $b['order'];
});
但它没有返回数组,而是返回“sku”和数字。
答案 0 :(得分:0)
将urn
列提取到单个维度,按降序排序并按原样排序原始数组:
count
答案 1 :(得分:-2)
您可以使用array_multisort或usort
工作解决方案:
function sortBySubValue($array, $value, $asc = true, $preserveKeys = false)
{
if ($preserveKeys) {
$c = array();
if (is_object(reset($array))) {
foreach ($array as $k => $v) {
$b[$k] = strtolower($v->$value);
}
} else {
foreach ($array as $k => $v) {
$b[$k] = strtolower($v[$value]);
}
}
$asc ? asort($b) : arsort($b);
foreach ($b as $k => $v) {
$c[$k] = $array[$k];
}
$array = $c;
} else {
if (is_object(reset($array))) {
usort($array, function ($a, $b) use ($value, $asc) {
return $a->{$value} == $b->{$value} ? 0 : ($a->{$value} - $b->{$value}) * ($asc ? 1 : -1);
});
} else {
usort($array, function ($a, $b) use ($value, $asc) {
return $a[$value] == $b[$value] ? 0 : ($a[$value] - $b[$value]) * ($asc ? 1 : -1);
});
}
}
return $array;
}
sortBySubValue($array, 'count', false, true);