我有以下数组:
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'
)
我将首先提取年份部分并按值对其进行排序,同时仍然使用 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];
}
仅供参考,有一堆函数可以处理 PHP 中的排序数组。
我认为您的数组更好的组织是这样的:
[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
)
)