1

I have searched SO and Google and have found lots of similar questions, but nothing that fits my exact use case.

I have an array of arrays like this:

Array
(
    [0] => Array
        (
            [id] => c80c5133-1140-8187-ad3b-524b4ed0f1a8
            [date_entered] => 10/01/2013 03:38pm
        )

    [1] => Array
        (
            [id] => 176815c6-b57f-7643-0f08-524b4f22b51c
            [date_entered] => 10/01/2013 03:42pm
        )

    [2] => Array
        (
            [id] => df0f8824-0b12-b92e-1d2e-524c6cb19c41
            [date_entered] => 10/02/2013 11:56am
        )

)

I need to rename the keys of the first dimension to be the value of the date_entered key in the second dimension arrays like this so that I can (hopefully) sort the array by the most recent date. I need to preserve the contents of each array because I will need to grab the ID that corresponds to the correct date.

Array
(
    [10/01/2013 03:38pm] => Array
        (
            [id] => c80c5133-1140-8187-ad3b-524b4ed0f1a8
            [date_entered] => 10/01/2013 03:38pm
        )

    [10/01/2013 03:42pm] => Array
        (
            [id] => 176815c6-b57f-7643-0f08-524b4f22b51c
            [date_entered] => 10/01/2013 03:42pm
        )

    [10/02/2013 11:56am] => Array
        (
            [id] => df0f8824-0b12-b92e-1d2e-524c6cb19c41
            [date_entered] => 10/02/2013 11:56am
        )

)

I am trying to do it like this (which is obviously not correct) but for the life of me I still can't get it.

foreach ($array as $key) {
    foreach ($key as $subkey => $subvalue) {
        if ($subkey == 'date_entered') {
            // change the name of the key?
        }
    }
}

I am really struggling with multidimensional arrays and manipulating them, no matter how much I read and practice! Can anyone help?

  • I think you could really sort it better quite easily: http://stackoverflow.com/questions/2699086/sort-multidimensional-array-by-value-2 – d-wade Oct 03 '13 at 19:56

1 Answers1

4

This code should do it:

$newArray = array();

foreach ($array as $id => $dataset) {
  $newArray[ $dataset['date_entered'] ] = $dataset;
}

I created a new array here because "changing the array within a foreach loop may lead to unexpected behaviour" (source).

If you really need to preserve your original array, you can use your numeric indices for accessing the elements:

$arrCount = count($array);
for ($i=0; $i<$arrCount; $i++) {
  $array[ $dataset['date_entered'] ] = $array[$i];
  unset($array[$i]);
}

All elements get copied before they get unset/deleted at the previous key.

ComFreek
  • 29,044
  • 18
  • 104
  • 156
  • 1
    Thank you, this worked! Also, thank you for showing the alternate method of preserving the original array as well as the link to the explanation. – Get-ForumUserName Oct 03 '13 at 19:59