PHP:在其他键下移动数组的值

时间:2015-07-25 14:02:17

标签: php arrays

我有这个数组:

Array
(
    [0] => Array
        (
            [id] => 1
            [amount_positive] => 10.00
            [negative_sum] => -5,7
            [negative] => Array
                (
                    [0] => Array
                        (

                            [amount] => -3.00
                        )

                    [1] => Array
                        (

                            [amount] => -2.00
                        )

                    [2] => Array
                        (

                            [amount] => -0.70
                        )

                )

        )

    [1] => Array
        (
            [id] => 13
            [amount_positive] => 6.00
            [negative_sum] => -7
            [negative] => Array
                (
                    [0] => Array
                        (

                            [amount] => -7
                        )

                )

        )

)

您可以注意到,键0的正数为+10.00,负数为-5.7(它们是货币交易)。

Key 1有+13和-7。

基本上,我需要迭代到数组并在键0下移动4.30,取自键1的NEGATIVE。

这必须是最后一个数组:

Array
(
    [0] => Array
        (
            [id] => 1
            [amount_positive] => 10.00
            [negative_sum] => -10.00
            [negative] => Array
                (
                    [0] => Array
                        (

                            [amount] => -3.00
                        )

                    [1] => Array
                        (

                            [amount] => -2.00
                        )

                    [2] => Array
                        (

                            [amount] => -0.70
                        )

                    [3] => Array
                        (
                            [amount] => -4.30
                        )

                )

        )

    [1] => Array
        (
            [id] => 13
            [amount_positive] => 6.00
            [negative_sum] => -2.70
            [negative] => Array
                (
                    [0] => Array
                        (

                            [amount] => -2.70
                        )

                )

        )

)

1 个答案:

答案 0 :(得分:0)

如果您需要在此特定阵列上执行转换的代码(您知道数组索引),以下内容将执行您想要的操作:

$expense = -4.30;

$your_array[0]['negative'][] = ['amount' => $expense];
$your_array[0]['negative_sum'] +=  $expense;


$your_array[1]['negative'][0]['amount'] -= $expense;
$your_array[1]['negative_sum'] -=  $expense;

如果你想要一个更多的"一般"对于任意索引和任意amount条目的方法,您需要从更广泛的角度重新解释您的问题。