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 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?