如何用前序已填充数组值填补空值?PHP代码优化需求
Solution
To get your desired output, you need to track all the necessary values from the last valid (non-null $value[0]) entry and reuse them when you hit null entries. Here's the adjusted code:
$array = unserialize(file_get_contents('file/temp/'.$request->name_file)); // Initialize variables to store the last valid full set of values $lastValid2 = ''; $lastValid3 = ''; $lastValid4 = ''; $lastValid5 = ''; foreach ($array[0] as $key => $value) { if ($key > 11) { if ($value[0]) { // Update our stored values with the current valid entry $lastValid2 = $value[2]; $lastValid3 = $value[3]; $lastValid4 = $value[4]; $lastValid5 = $value[5]; // Output the current valid line echo "{$lastValid2} | {$lastValid3} | {$lastValid4} | {$lastValid5} | <br>"; } elseif (is_null($value[0])) { // Only output if we have a previous valid entry to avoid empty lines if (!empty($lastValid2)) { // Reuse the last valid values to print the full line echo "{$lastValid2} | {$lastValid3} | {$lastValid4} | {$lastValid5} | <br>"; } } } }
What Changed & Why:
- Track All Required Values: Instead of only saving
$value[2]in$a, we now store all four values ($value[2]to$value[5]). This lets us recreate the full line format whenever we need it. - Replace Null Entry Output: When
$value[0]is null, we no longer print "=>kosong"—we use the stored values from the last valid entry to output an exact copy of that line. - Avoid Empty Lines: We added a check
!empty($lastValid2)to make sure we don't print blank lines if the first entries (after key 11) are null (before any valid data is found).
This code will produce the exact output you're expecting, replacing every "=>empty" line with the full content from the last non-null entry.
内容的提问来源于stack exchange,提问作者Fikri Ali Thaufik
相关产品推荐
相关产品推荐

