使用PHP排序的二维数组

时间:2015-01-12 12:07:02

标签: php arrays

我的代码是:

$arr = array(
    array(
        "title" => "Volvo"
    ),
    array(
        "title" => "BMW"
    ),
    array(
        "title" => "Saab"
    ),
    array(
        "title" => "Aam"
    )
);

$a = aasort($arr,"title");

echo "<pre>",print_r($a),"</pre>";

function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    natcasesort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
    return $array;
}

,输出为:

Array
(
[3] => Array
    (
        [title] => Aam
    )

[1] => Array
    (
        [title] => BMW
    )

[2] => Array
    (
        [title] => Saab
    )

[0] => Array
    (
        [title] => Volvo
    )

)
1

但我希望输出如下:

Array
(
[0] => Array
    (
        [title] => Aam
    )

[1] => Array
    (
        [title] => BMW
    )

[2] => Array
    (
        [title] => Saab
    )

[3] => Array
    (
        [title] => Volvo
    )

)
1

怎么做?

3 个答案:

答案 0 :(得分:0)

您可以使用array_values()重新索引数组:

$array = array_values($ret);

答案 1 :(得分:0)

试试这会对您有所帮助:

   $result = array();

  $result = sortArray($array,'key');

这里,$array是未排序的数组。因此,您可以通过调用sortArray函数对其进行排序。

<?php

function sortArray($arrData, $p_sort_field, $p_sort_type = false )
{
 if(!empty($arrData))
 {
  foreach($arrData as $data)
  {
   $newData [] = $data;
  }
  for($i=0; $i<count($newData); $i++)
  {
    $ar_sort_field[$i]=$newData[$i][$p_sort_field];
  }
  array_multisort($ar_sort_field, ($p_sort_type ? SORT_DESC : SORT_ASC), $newData);
  return $newData;
 }
}

?>

答案 2 :(得分:0)

试试这个..

$arr  = array(
    array(
    "title" => "Volvo"
    ),
    array(
    "title" => "BMW"
    ),
    array(
    "title" => "Saab"
    ),
    array(
    "title" => "Aam"
    )
    );

$arr  = msort($arr, array('title'));

print_r($arr);

function msort($array, $key, $sort_flags = SORT_REGULAR) {
    if (is_array($array) && count($array) > 0) {
        if (!empty($key)) {
            $mapping = array();
            foreach ($array as $k => $v) {
                $sort_key = '';
                if (!is_array($key)) {
                    $sort_key = $v[$key];
                } else {
                    // @TODO This should be fixed, now it will be sorted as string
                    foreach ($key as $key_key) {
                        $sort_key .= $v[$key_key];
                    }
                    $sort_flags = SORT_STRING;
                }
                $mapping[$k] = $sort_key;
            }
            asort($mapping, $sort_flags);
            $sorted = array();
            foreach ($mapping as $k => $v) {
                $sorted[] = $array[$k];
            }
            return $sorted;
        }
    }
    return $array;
}

<强>结果

    Array ( [0] => Array ( [title] => Aam ) [1] => Array ( [title] => BMW ) 
[2] => Array ( [title] => Saab ) [3] => Array ( [title] => Volvo ) )`