根据数组的一部分在PHP中对多维数组进行排序

时间:2012-06-12 09:45:50

标签: php arrays multidimensional-array

我有以下数组:

items = array(
        'note' => array(),
        'text' => array(),
        'year' => array()
        )

所以我有:

[note] => Array
(
   [0] => 'note1'
   [1] => 'note2'
   [2] => 'note3'
), 
[text] => Array
(
   [0] => 'text1'
   [1] => 'text2'
   [2] => 'test3'
), 
[year] => Array
(
   [0] => '2002'
   [1] => '2000'
   [2] => '2011'
)

我想按年安排上述阵列。但是当移动元素时,我想移动其他数组中的相应元素(注释,文本)。

例如:

[note] => Array
(
   [2] => 'note3'
   [0] => 'note1'
   [1] => 'note2'
), 
[text] => Array
(
   [2] => 'text3'
   [0] => 'text1'
   [1] => 'test2'
), 
[year] => Array
(
   [2] => '2011'
   [0] => '2002'
   [1] => '2000'
)

2 个答案:

答案 0 :(得分:4)

我首先使用arsort()提取年份部分并按值对其进行排序,同时仍保持密钥:

$yearData = $array['year'];
arsort($yearData);//sort high-to-low by value, while maintain it's key.

最后,使用这个新分类的年份对数据进行排序:

$newArray['note'] = array();
$newArray['text'] = array();
$newArray['year'] = array();

foreach($yearData as $key => $value){
    $newArray['note'][$key] = $array['note'][$key];
    $newArray['text'][$key] = $array['text'][$key];
    $newArray['year'][$key] = $array['year'][$key];
}

仅供参考,有a bunch of functions that deal with sorting arrays in PHP

答案 1 :(得分:0)

我认为你的阵列更好的组织将是这样的:

[0] => Array(
    'note' => note1, 'text' => 'text1', 'year' => '2002)
[1] => Array(
    'note' => note2, 'text' => 'text2', 'year' => '2000)
[2] => Array(
    'note' => note3, 'text' => 'text4', 'year' => '2011)

这样,每个相关项目都保持在一起,并且更容易按所需类型对它们进行排序。

$items = array(
    array(
        'note' => value,
        'text' => value,
        'year' => value
        ),
    array(
        'note' => value,
        'text' => value,
        'year' => value
        )
    )