问题描述
如何按值对多维数组进行排序,但顺序要自定义?
How do I sort a multidimensional array by a value, but with a custom order?
多维数组将类似于:
$attribute_content[0]['term_id'] = 76;
$attribute_content[0]['content'] = "ratio";
$attribute_content[1]['term_id'] = 18;
$attribute_content[1]['content'] = "ideal condition";
$attribute_content[2]['term_id'] = 164;
$attribute_content[2]['content'] = "genotype";
$attribute_content[3]['term_id'] = 218;
$attribute_content[3]['content'] = "genetics";
$attribute_content[4]['term_id'] = 60;
$attribute_content[4]['content'] = "height";
,并且排序是根据term_id进行的,但是将是:
and the ordering is according to the term_id, but will be:
$order = array(18,164,218,60,76);
我尝试了以下代码对数组进行重新排序,但似乎是随机的:
I've tried the following codes which re-order the array, but seemingly randomly:
usort($attribute_content, function ($a, $b) use ($order) {
$pos_a = array_search($a, $order);
$pos_b = array_search($b, $order);
return $pos_a - $pos_b;
});
和
$weights = array_flip($order);
usort($attribute_content, function($x, $y) use($weights) {
return $weights[$x['term_id']] - $weights[$y['term_id']];
});
请帮助
推荐答案
您的 usort
无法正常工作,因为其中的 $ a
和 $ b
回调函数并不完全符合您的想法.它们不是'term_id'
值.它们是整个内部数组,例如
Your usort
is not working because $a
and $b
in the callback function are not quite what you think they are. They aren't 'term_id'
values. They are the entire inner array, e.g.
array('term_id' => 76, 'content' => 'ratio')
因此,将它们用作 array_search
与您的 $ order
数组的参数将不起作用,因为它们不在该数组中.所有 array_search
都将返回 false
,因此看似随机.您只需要指定 term_id
键,就像这样,它将按预期工作:
So using them as an argument to array_search
with your $order
array won't work, because they aren't in that array. All the array_search
es will just return false
, hence the seemingly random sort. You just need to specify the term_id
key, like this, and it will work as expected:
usort($attribute_content, function ($a, $b) use ($order) {
$pos_a = array_search($a['term_id'], $order);
$pos_b = array_search($b['term_id'], $order);
return $pos_a - $pos_b;
});
就您尝试的第二种方法而言,我真的不确定是什么问题.它似乎正常工作: https://3v4l.org/oJhJs
这篇关于PHP按自定义顺序对多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!