如何在PHP中的关联数组中更新特定键的值?

2022-08-30 09:13:07

我有一个名为$data

Array
(
    [0] => Array
        (
            [transaction_user_id] => 359691e27b23f8ef3f8e1c50315cd506
            [transaction_no] => 19500912050218
            [transaction_total_amount] => 589.00
            [transaction_date] => 1335932419
            [transaction_status] => cancelled
        )

    [1] => Array
        (
            [transaction_user_id] => 9def02e6337b888d6dbe5617a172c18d
            [transaction_no] => 36010512050819
            [transaction_total_amount] => 79.00
            [transaction_date] => 1336476696
            [transaction_status] => cancelled
        )

    [2] => Array
        (
            [transaction_user_id] => 9def02e6337b888d6dbe5617a172c18d
            [transaction_no] => 19020512050820
            [transaction_total_amount] => 299.00
            [transaction_date] => 1336476739
            [transaction_status] => cancelled
        )

    [3] => Array
        (
            [transaction_user_id] => 9def02e6337b888d6dbe5617a172c18d
            [transaction_no] => 27050512050821
            [transaction_total_amount] => 79.00
            [transaction_date] => 1336476927
            [transaction_status] => cancelled
        )

    [4] => Array
        (
            [transaction_user_id] => 8e9050a3646c98342b9ba079fba80982
            [transaction_no] => 12070512050822
            [transaction_total_amount] => 129.00
            [transaction_date] => 1336477032
            [transaction_status] => cancelled
        )

)

我想将键的值转换为用户可读的格式(即mm / dd / yyyy)。为此,我在一个返回整个数组的函数中编写了以下代码:[transaction_date]

 foreach($data as $value)
 {
    $value[transaction_date]=date('d/m/Y',$value[transaction_date]);
 }
    
 return $data;

我的问题是,我在不更改所有数组元素的值的情况下获得了相同的数组。实际上,应返回具有 更新值的数组。任何人都可以帮我解决这个问题吗?提前致谢。[transaction_date][transaction_date]


答案 1

将 foreach 更改为类似这样的内容,在执行操作后,您不会将数据重新分配给返回变量。$data

foreach($data as $key => $value)
{
  $data[$key]['transaction_date'] = date('d/m/Y',$value['transaction_date']);
}

密码键盘演示。


答案 2

这也行得通!

foreach($data as &$value) {
  $value['transaction_date'] = date('d/m/Y', $value['transaction_date']);
}

是的,替代品!