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

时间:2016-07-18 21:04:03

标签: php arrays multidimensional-array

如何按值对多维数组进行排序,但使用自定义顺序?

多维数组将类似于:

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

请帮忙

4 个答案:

答案 0 :(得分:0)

这就是我要做的事情:

$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,或者只是想重命名并使用它,则可以删除该行。

答案 1 :(得分:0)

这是使用array_multisort()的另一种方法:

<?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>';

答案 2 :(得分:0)

您的usort无效,因为回调函数中的$a$b并不是您认为的那样。它们不是'term_id'值。它们是整个内部数组,例如

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

因此,使用它们作为array_search$order数组的参数将不起作用,因为它们不在该数组中。所有array_search es将只返回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

答案 3 :(得分:0)

另一种方法,只需将订单添加到数组并使用它进行排序:

$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'];
});
相关问题