doudiyu1639 2013-10-03 19:44
浏览 31
已采纳

重命名多维关联数组中的键

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?

  • 写回答

1条回答 默认 最新

  • douque9982 2013-10-03 19:47
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)