我的数据库中有两个json字符串,它们包含了我试图比较的数据,以便在活动日志中显示,以查看用户对条目的更改:old_properties和properties。
这是我现在的控制器:
$properties = json_decode($log->properties, true);
$old_properties = json_decode($log->old_properties, true);
$changes = array_diff($properties, $old_properties);这是我的刀刃
@foreach ($changes as $key => $value)
{{$key}}: {{$value}}<br>
@endforeach例如,如果我的数据是:
old_properties: 'name' => 'Matthew', 'state' => 'Oregon'
properties: 'name' => 'Samuel', 'state' => 'Oregon'我从我的$changes中看到的就是:name: Samuel
我试图显示的是:name: Matthew -> Samuel,或者其他一些方式来显示旧属性是什么,以及它在同一行中被更改为什么。
发布于 2018-11-07 20:54:44
看起来你可以这样做:
@foreach ($changes as $key => $value)
{{$key}}: {{$old_properties[$key]}} -> {{$value}}<br>
@endforeach发布于 2018-11-07 22:14:53
设置计算是否可以解决这个问题:
function printKeptAndUpdated ($setMapKeptAndUpdated, $setA, $setB) {
$changes = [];
foreach ($setMapKeptAndUpdated as $key => $value) {
$changes[] = $key . ": " . $setA[$key] . " -> " . $setB[$key];
}
echo("<pre>");
print_r($changes);
echo("</pre>");
}
$old_properties = [
"ape" => "black",
"cat" => "white",
"dog" => "black",
"fox" => "red",
];
$properties = [
"bear" => "brown",
"cat" => "white",
"dog" => "yellow",
"eagle" => "grey",
"fox" => "white",
"giraffe" => "yellow",
];
// Define 2 Set of array, setA is old set data, setB is new set data.
// Both setA and setB should only be one dimensional array
// which elements are always key => value pair only.
$setA = $old_properties;
$setB = $properties;
$setMap = [];
// Set map will do Set calculation in the future,
// and imply those 4 possibility: deleted, added, kept (updated or untouched),
// but only 3 of them are shown: deleted, added, kept.
// 4 possiblility after Set calculation.
$setMapDeleted = [];
$setMapAdded = [];
$setMapKeptAndUpdated = [];
$setMapKeptAndUntouched = [];
// Put $setA in $setMap first.
foreach($setA as $key => $value) {
$setMap[$key] = "a";
}
// Then put $setB in $setMap too.
foreach($setB as $key => $value) {
if (array_key_exists($key, $setMap)) {
$setMap[$key] = "ab";
} else {
$setMap[$key] = "b";
}
}
// So now the $setMap structure looks like this
// (just example, not as same as current data):
//$setMap = [
// "ape" => "b",
// "bear" => "ab",
// "cat" => "a",
// "dog" => "a",
// "eagle" => "b",
//];
// Where "a" = setA - setB, "b" = setB - setA, "ab" = setA ∩ setB (intersection)
// Now finish the Set calculation and also separate Set "kept" to set "updated" and Set "untouched".
foreach($setMap as $key => $value) {
if ($value === "a") {
$setMapDeleted[$key] = $setA[$key];
} elseif ($value === "b") {
$setMapAdded[$key] = $setB[$key];
} elseif ($value === "ab") {
if ($setB[$key] === $setA[$key]) {
$setMapKeptAndUntouched[$key] = $setB[$key];
} else {
$setMapKeptAndUpdated[$key] = $setB[$key];
}
}
}
printKeptAndUpdated($setMapKeptAndUpdated, $setA, $setB);
// Print the result you want.https://stackoverflow.com/questions/53195758
复制相似问题