对多维数组进行排序和分组

时间:2013-06-13 12:50:45

标签: php multidimensional-array

我有一个多维数组,例如:

Array
(
    [0] => Array
        (
            [quick_filter] => best_of_web
            [id] => 1136
        )

    [1] => Array
        (
            [quick_filter] => org_content
            [id] => 1139
        )

    [2] => Array
        (
            [quick_filter] => org_content
            [id] => 1141
        )

    [3] => Array
        (
            [quick_filter] => best_of_web
            [id] => 1143
        )

    [4] => Array
        (
            [quick_filter] => org_content
            [id] => 1144
        )

    [5] => Array
        (
            [quick_filter] => best_of_web
            [id] => 1145
        )

)

我希望按此顺序对其进行排序

Array
(
    [best_of_web]
    Array
    (
        [id] => Array
            (
                [0] => 1136
                [1] => 1143
                [2] => 1145
            )
    )

    [org_content]
    Array
    (
        [id] => Array
            (
                [0] => 1139
                [1] => 1141
                [2] => 1144
            )
    )
)

3 个答案:

答案 0 :(得分:2)

尝试以下方法:

$output_array = array();
foreach ($input_array as $item) {
    if (!isset($output_array[$item['quick_filter']]['id'])) {
        $output_array[$item['quick_filter']]['id'] = array();
    }
    $output_array[$item['quick_filter']]['id'][] = $item['id'];
}

$input_array替换为您想要排序的数组。

答案 1 :(得分:1)

怎么样..

$resultArray = array();
foreach ($sourceArray as $key=>$value){

   if (!isset($resultArray[$value['quick_filter']]))

      /* set a new key to $resultArray */
      $resultArray[$value['quick_filter']]['id'] = array($value['id']);

   } else {

      /* add id to $resultArray*/
      $resultArray[$value['quick_filter']]['id'][] = $value['id'];

   }
}

答案 2 :(得分:1)

这是怎么回事:

$merged = array();
foreach ($array as $index) $merged[$index['quick_filter']]['id'][] = $index['id'];
print_r($merged);