0

I have the following array:

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

So I have:

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

And I would like to arrange the above arrays by year. but when moving elements I would like to move the corresponding elements in other arrays(note,text).

For example:

[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 Answers 2

4

I would first extract the year part and sort it by value, while still maintaining the key, using arsort():

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

Finally, sort the data using this newly sorted year:

$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];
}

FYI, there are a bunch of functions that deal with sorting arrays in PHP.

Sign up to request clarification or add additional context in comments.

Comments

0

I think a better organization to your array would be something like this:

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

This way, each related item stays together and it's easier to sort them by the desired type.

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

2 Comments

Yes I know but unfortunately I cannot change the whole structure.
I saw that coming :P Well, @ariefbayu answer will solve it for you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.