简体   繁体   English

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

[英]how to replace key-value pair to another key-value in multidimensional array

I have a multidimensional array with an arbitrary number of arrays. 我有一个任意数量的数组的多维数组。

The array is called charge_codes . 该数组称为charge_codes

print_r( $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
        )

)

I am trying to loop through the array and find the amount for charge code 62 and assign it to the amount for charge code 21. Once The amount has been assigned to charge code 21, I need to remove the array with charge code 62. 我试图遍历数组,找到费用代码62的金额,并将其分配给费用代码21的金额。一旦将金额分配给费用代码21,我需要删除费用代码为62的阵列。

Result I am wanting 结果我想要

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
            ) 

    )

Should i loop through using foreach( $charge_codes as $key = > $value ) ? 我应该循环使用foreach( $charge_codes as $key = > $value )吗?

    $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);

Try this code. 试试这个代码。

<?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]); 
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM