PHP中能否在数组内部使用自身元素的值进行计算?
PHP数组中用当前元素的amount计算price的正确实现
原代码的写法会直接报错,因为数组在初始化过程中,$AMOUNTS变量还未完成赋值,内部引用$AMOUNTS[0]['amount']这类索引时,PHP会判定变量未定义或者索引不存在。以下是几种可行的实现方式:
方案一:先定义基础数组,再遍历补充price
先创建仅包含amount的数组,再通过循环为每个元素计算并添加price字段,这是最直观的实现方式:// 初始化仅含amount的数组 $AMOUNTS = [ ['amount' => '10'], ['amount' => '50'], ['amount' => '70'], ]; // 遍历数组计算price,使用引用修改原数组元素 foreach ($AMOUNTS as $key => &$item) { $amount = (int)$item['amount']; // 转换为数值类型,避免字符串运算问题 // 根据元素索引对应系数计算price $coefficient = match($key) { 0 => 3, 1 => 2, 2 => 1, }; $item['price'] = $amount * $coefficient; } unset($item); // 释放引用,防止后续操作意外修改数组方案二:基于规律数据批量生成
如果amount和对应系数有明确的对应关系,可以拆分数据源批量生成目标数组:$coefficients = [3, 2, 1]; // 每个amount对应的计算系数 $amountList = ['10', '50', '70']; // 原始amount列表 $AMOUNTS = []; foreach ($amountList as $index => $amountStr) { $amount = (int)$amountStr; $AMOUNTS[] = [ 'amount' => $amountStr, 'price' => $amount * $coefficients[$index], ]; }方案三:用array_map一次性处理
借助array_map函数,在初始化数组的同时完成price计算,适合一次性构建数组的场景:$AMOUNTS = array_map(function($item) { $amount = (int)$item['amount']; // 根据amount值匹配对应系数计算price $price = match($item['amount']) { '10' => $amount * 3, '50' => $amount * 2, '70' => $amount * 1, }; return [ 'amount' => $item['amount'], 'price' => $price, ]; }, [ ['amount' => '10'], ['amount' => '50'], ['amount' => '70'], ]);
内容的提问来源于stack exchange,提问作者Jimski
相关产品推荐
相关产品推荐

