Ibrahim Hafiji
Ibrahim Hafiji

Reputation: 150

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.

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.

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

Upvotes: 0

Views: 374

Answers (2)

Dinesh Patra
Dinesh Patra

Reputation: 1135

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

Upvotes: 0

SRK
SRK

Reputation: 3496

    $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.

Upvotes: 1

Related Questions