如何将键值对替换为多维数组中的另一个键值

时间:2018-03-21 11:37:53

标签: php arrays multidimensional-array foreach

我有一个具有任意数量数组的多维数组。

该数组名为charge_codes

print_r($ charge_codes)

Array
(
    [0] => Array
        (
            [charge_code] => 21
            [amount] => 134.57
        )

    [1] => Array
        (
            [charge_code] => 4
            [amount] => 8.05
        )

    [2] => Array
        (
            [charge_code] => 23
            [amount] => 1.68
        )

    [3] => Array
        (
            [charge_code] => 62
            [amount] => 134.12
        )

)

我正在尝试遍历数组并找到费用代码62的金额并将其分配给费用代码21的金额。一旦将金额分配给费用代码21,我需要使用费用代码删除数组62。

我想要的结果

Array
(
        [0] => Array
            (
                [charge_code] => 21
                [amount] => 134.12
            )

        [1] => Array
            (
                [charge_code] => 4
                [amount] => 8.05
            )

        [2] => Array
            (
                [charge_code] => 23
                [amount] => 1.68
            ) 

    )

我应该使用foreach( $charge_codes as $key = > $value )吗?

2 个答案:

答案 0 :(得分:1)

    $change_key = 0;
    $amount = 0;

    foreach($charge_codes as $key=>$value){
     if($value["charge_code"] == 21)
     {
      $change_key = $key;
     }
     if($value["charge_code"] == 62)
     {
      $amount = $value["amount"];
      unset($charge_codes[$key]);
     }
    }

    if($amount != 0){
     $charge_codes[$change_key]["amount"] = $amount;
    }
    print_r($charge_codes);

试试这段代码。

答案 1 :(得分:0)

<?php
$arr = [
    ["charge_code" => 21, "amount" => 134.57],
    ["charge_code" => 4, "amount" => 8.05],
    ["charge_code" => 23, "amount" => 1.68],
    ["charge_code" => 62, "amount" => 134.12] 
];

/**
* @Function to search the index from array
*
* @Args: charge code
*
* @Returns: null | index
*/
function searchIndexByChargeCode($chargeCode) {
    global $arr;
    foreach ($arr as $index=>$vals) {
        if (!empty($vals["charge_code"])) {
            if ($vals["charge_code"] == $chargeCode) {
                return $index;
            }
        }
    }
    return null; 
}

$index62 = searchIndexByChargeCode(62);
$index21 = searchIndexByChargeCode(21);
$arr[$index21]["amount"] = $arr[$index62]["amount"];
unset($arr[$index62]); 
?>