[英]how to replace key-value pair to another key-value in multidimensional array
我有一個任意數量的數組的多維數組。
該數組稱為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 )
嗎?
$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);
試試這個代碼。
<?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.