0

我有这样的多维数组:

array(1) {
  ["category_content"]=>
  array(3) {
    [0]=>
    array(5) {
      ["content_id"]=>
      string(1) "2"
      ["content_title"]=>
      string(6) "coolas"
      ["grade"]=>
      string(1) "1"
      ["content_order"]=>
      string(1) "1"
      ["kind"]=>
      string(7) "article"
    }
    [1]=>
    array(5) {
      ["content_id"]=>
      string(1) "1"
      ["content_title"]=>
      string(16) "Zango Restaurant"
      ["grade"]=>
      string(1) "2"
      ["content_order"]=>
      string(1) "2"
      ["kind"]=>
      string(8) "business"
    }
  }
}

我想按 content_order 排序。如何使用多重排序对这个数组进行排序?以及如何提供用于排序的标志?提前致谢

4

4 回答 4

2
$category_content_array = $data_array; // your actual data array
$content_order_array = array();  // new array as a column to sort collector

foreach ($category_content_array as $content) {
$content_order_array[] = $content['content_order'];
}

array_multisort($content_order_array, SORT_ASC, $category_content_array);
于 2013-02-11T04:01:02.200 回答
1

这将帮助您解决问题。

<?php
function CustomSort (&$array, $key)
{
    $sorter=array();
    $ret=array();

    reset($array);

    foreach ($array as $ii => $va)
    {
        $sorter[$ii]=$va[$key];
    }

    asort($sorter);

    foreach ($sorter as $ii => $va)
    {
        $ret[$ii]=$array[$ii];
    }

    $array=$ret;
}

CustomSort($your_array,"content_id");

?>

另一个是

$contentID = array();
foreach ($your_array as $key => $row)
{
    $contentID[$key] = $row['content_id'];
}
array_multisort($contentID, SORT_DESC, $your_array);
于 2013-02-11T03:54:05.750 回答
1

http://www.php.net/manual/en/function.array-multisort.php

示例#3,

<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);

foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>
于 2013-02-11T03:57:29.597 回答
0

你也可以使用usort(). 例如,

<?php
$array = array (
    '1' => array('sortBy' => 10),
    '2' => array('sortBy' => 4),
    '3' => array('sortBy' => 50),
    '4' => array('sortBy' => 8),
    '5' => array('sortBy' => 2),
    '6' => array('sortBy' => 100),
);

function comp($a, $b) {
    return $a['sortBy'] > $b['sortBy'];
}

usort($array, comp);
?>
于 2013-02-11T03:59:58.660 回答