
在数据处理过程中,我们经常会遇到需要根据一个“基准”数据集来更新另一个“实际”数据集的情况。具体而言,假设我们有两个嵌套的数组或laravel集合,结构如下:
基准数据 ($first):
$first = [
"name" => "Test A",
"scores" => [
["name" => "Values", "points" => 9],
["name" => "Algebra", "points" => 6],
["name" => "Science", "points" => 5],
["name" => "Total", "points" => 20]
]
];实际数据 ($second):
$second = [
"name" => "Test A",
"scores" => [
["name" => "Values", "points" => 5],
["name" => "Algebra", "points" => 8],
["name" => "Total", "points" => 13]
]
];我们的目标是生成一个新的数据结构,它以 $first['scores'] 的结构为基础,但其中的 points 值应根据 $second['scores'] 进行更新。如果 $first['scores'] 中存在的某个 name 在 $second['scores'] 中没有对应的项,则其 points 值应设置为 0。
期望的输出结果如下:
立即学习“PHP免费学习笔记(深入)”;
[
"name" => "Test A",
"scores" => [
["name" => "Values", "points" => 5],
["name" => "Algebra", "points" => 8],
["name" => "Science", "points" => 0], // Science 在 $second 中缺失,设置为 0
["name" => "Total", "points" => 13]
]
]直接使用 Laravel 集合的 diffKeys 等方法并不能直接实现这种复杂的合并逻辑,因为它们主要用于比较键的差异,而非值更新和缺失填充。例如,diffKeys 会返回在第一个集合中存在但在第二个集合中不存在的键值对,这与我们期望的更新和填充行为不符。
为了高效地实现上述目标,我们可以采用一种基于 PHP 引用(&)的两阶段遍历方法。这种方法的核心思想是:首先,将基准数据中所有 points 初始化为 0,并建立一个通过 name 快速访问 points 的引用映射;然后,遍历实际数据,利用引用映射直接更新基准数据中的 points 值。
<?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]
]
];
// 第一阶段:初始化基准数据并建立引用映射
$refPoints = [];
foreach ($first['scores'] as $index => &$scoreItem) { // 注意这里对 $scoreItem 使用了引用
$scoreItem['points'] = 0; // 默认所有 points 为 0
$refPoints[$scoreItem['name']] = &$scoreItem['points']; // 建立 name 到 points 的引用
}
// 第二阶段:根据实际数据更新 points
foreach ($second['scores'] as $scoreItem) {
$name = $scoreItem['name'];
$points = $scoreItem['points'];
if (isset($refPoints[$name])) {
$refPoints[$name] = $points; // 通过引用直接更新 $first 中的 points
}
}
// 输出最终结果
var_export($first);
?>初始化基准数据与建立引用映射:
$refPoints = [];
foreach ($first['scores'] as $index => &$scoreItem) {
$scoreItem['points'] = 0;
$refPoints[$scoreItem['name']] = &$scoreItem['points'];
}根据实际数据更新 points:
foreach ($second['scores'] as $scoreItem) {
$name = $scoreItem['name'];
$points = $scoreItem['points'];
if (isset($refPoints[$name])) {
$refPoints[$name] = $points;
}
}通过这种两阶段的遍历和引用机制,我们能够高效、准确地实现嵌套集合的更新与缺失值填充,生成符合预期的数据结构。
以上就是PHP/Laravel:高效更新嵌套集合并填充缺失数据点的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号