
本文旨在解决在Laravel中,如何基于第二个集合/数组的值来更新第一个集合/数组的值,并且当第二个集合/数组中不存在对应项时,将第一个集合/数组中的值置为0的问题。我们将提供一种高效且简洁的方法,通过引用和查找表来实现这一目标,避免使用复杂的集合操作。
该方案的核心思想是:首先遍历第一个数组,将其 points 值初始化为 0,并建立一个 name 到 points 的引用查找表。然后,遍历第二个数组,利用查找表将第二个数组中的 points 值更新到第一个数组中对应的 points 引用。
以下是具体实现步骤和代码示例:
准备数据
假设我们有两个数组 $first 和 $second,结构如下:
$first = [
"name" => "Test A",
"scores" => [
["name" => "Values", "points" => 9],
["name" => "Algebra", "points" => 6],
["name" => "Science", "points" => 5],
["name" => "Total", "points" => 20]
]
];
$second = [
"name" => "Test A",
"scores" => [
["name" => "Values", "points" => 5],
["name" => "Algebra", "points" => 8],
["name" => "Total", "points" => 13]
]
];初始化并创建查找表
遍历 $first['scores'],将每个元素的 points 初始化为 0,并创建一个 $refPoints 数组,用于存储 name 到 points 的引用。
foreach ($first['scores'] as ['name' => $name, 'points' => &$points]) {
$points = 0;
$refPoints[$name] =& $points;
}注意: & 符号表示引用。$refPoints[$name] =& $points; 创建了一个 $refPoints[$name] 到 $points 的引用。这意味着,修改 $refPoints[$name] 的值,也会同时修改 $points 的值。
更新 points 值
遍历 $second['scores'],使用 $refPoints 查找表更新 $first['scores'] 中对应的 points 值。
foreach ($second['scores'] as ['name' => $name, 'points' => $refPoints[$name]]);
由于 $refPoints[$name] 是 $points 的引用,所以这一步直接修改了 $first['scores'] 中的 points 值。
查看结果
执行完以上步骤后,$first 数组将被更新为期望的结果:
var_export($first);
输出:
array (
'name' => 'Test A',
'scores' =>
array (
0 =>
array (
'name' => 'Values',
'points' => 5,
),
1 =>
array (
'name' => 'Algebra',
'points' => 8,
),
2 =>
array (
'name' => 'Science',
'points' => 0,
),
3 =>
array (
'name' => 'Total',
'points' => 13,
),
),
)<?php
$first = [
"name" => "Test A",
"scores" => [
["name" => "Values", "points" => 9],
["name" => "Algebra", "points" => 6],
["name" => "Science", "points" => 5],
["name" => "Total", "points" => 20]
]
];
$second = [
"name" => "Test A",
"scores" => [
["name" => "Values", "points" => 5],
["name" => "Algebra", "points" => 8],
["name" => "Total", "points" => 13]
]
];
foreach ($first['scores'] as ['name' => $name, 'points' => &$points]) {
$points = 0;
$refPoints[$name] =& $points;
}
foreach ($second['scores'] as ['name' => $name, 'points' => $refPoints[$name]]);
var_export($first);
?>该方法利用引用和查找表,避免了复杂的集合操作,提高了效率。适用于需要基于第二个集合/数组更新第一个集合/数组,并且当第二个集合/数组中不存在对应项时,需要将第一个集合/数组中的值置为默认值(例如 0)的场景。
以上就是基于Laravel集合/数组更新首个集合/数组的值,若不存在则置为0的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号