如何在 PHP 的关联数组中更新特定键的值? [英] How to update specific key's value in an associative array in PHP?

查看:41
本文介绍了如何在 PHP 的关联数组中更新特定键的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 $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
        )

)

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

and I want to convert the value of key [transaction_date] into user readable format (i.e. mm/dd/yyyy). For that I written the following code in a function which returns the whole array:

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

    return $data;

我的问题是我得到了相同的数组,而没有更改所有数组元素的 [transaction_date] 的值.实际上,期望返回带有 [transaction_date] 更新值的数组.谁能帮我解决这个问题?提前致谢.

My problem is I'm getting the same array without changing the value of [transaction_date] for all the array elements. Actually array with updated values for [transaction_date] is expected to be returned. Can anyone help me out to resolve this issue? Thanks in advance.

推荐答案

将您的 foreach 更改为这样的内容,在对其执行操作后,您没有将数据分配回返回变量 $data.

Change your foreach to something like this, You are not assigning data back to your return variable $data after performing operation on that.

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

键盘演示.

这篇关于如何在 PHP 的关联数组中更新特定键的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆