PHP使用自定义顺序对多维数组进行排序


PHP sort multidimensional array with 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,但是将是:

$order = array(18,164,218,60,76);

我尝试了以下代码来重新排列数组,但似乎是随机的:

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']];
});

请帮助

下面是使用array_multsort()的另一种方法:

<?php
$order = array(18,164,218,60,76);
$attribute_content = array(
    array('term_id' => 76, 'content' => 'ratio'),
    array('term_id' => 18, 'content' => 'ideal condition'),
    array('term_id' => 164,'content' => 'genotype'),
    array('term_id' => 218,'content' => 'genetics'),
    array('term_id' => 60, 'content' => 'height')
);
foreach($attribute_content as $k=>$r){
    $term_id = $r['term_id'];
    $custom_order = 0;
    if( in_array($term_id,$order) ){
        $custom_order = array_search($term_id,$order);
    }
    $tmp[] = $custom_order;
}
array_multisort($tmp,SORT_ASC,$attribute_content);
echo '<pre>',print_r($attribute_content),'</pre>';

还有一种方法,只需将顺序添加到数组中并使用它进行排序:

$order = array(18, 164, 218, 60, 76);
foreach ($attribute_content as $key => $values) {
    $attribute_content[$key]['order'] = array_search($values['term_id'], $order);
}
usort($attribute_content, function($a, $b) {
    return $a['order'] > $b['order'];
});

您的usort不工作,因为回调函数中的$a$b与您想象的不完全一样。它们不是'term_id'值。它们是整个内部阵列,例如

array('term_id' => 76, 'content' => 'ratio')

因此,在$order数组中使用它们作为array_search的参数是行不通的,因为它们不在该数组中。所有的array_searches只会返回false,因此看起来是随机排序。你只需要指定term_id密钥,就像这样,它就会按预期工作:

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

这就是我要做的:

$sortedArray = array();
for ($count = 0; $count < count($order); $count++) {
    for ($i = 0; $i < count($attribute_content); $i++) {
        if ($order[$count] == $attribute_content[$i]["term_id"]) {
            $sortedArray[count($sortedArray)] = $attribute_content[$i];
        }
    }
}
$attribute_content = $sortedArray;

它将循环遍历数组,并按照提供的顺序将值放入一个新的排序数组中。之后,它会将预先存在的数组设置为已排序的数组,但如果您不介意使用$sortedArray,或者您只想重命名并使用它,则可以删除该行。