翻翻过去那场雪
基本上你需要做的是对中的每个顶级数组$data,遍历 0 值数组(我称之为$blank)并查看当前$data数组中是否存在日期。如果是,请复制该值,否则使用空白值:$datafinal = array();foreach ($data as $key => $value) { foreach ($blank as $bkey => $bvalue) { if (($dkey = array_search($bvalue['dates'], array_column($value, 'dates'))) !== false) { $datafinal[$key][$bkey] = $value[$dkey]; } else { $datafinal[$key][$bkey] = $bvalue; } }}echo json_encode($datafinal, JSON_PRETTY_PRINT);输出:{ "EXPORT": [ { "dates": "2019-07-01", "c_job": 12 }, { "dates": "2019-07-02", "c_job": 8 }, { "dates": "2019-07-03", "c_job": 0 }, { "dates": "2019-07-04", "c_job": 11 } ], "IMPORT": [ { "dates": "2019-07-01", "c_job": 0 }, { "dates": "2019-07-02", "c_job": 0 }, { "dates": "2019-07-03", "c_job": 11 }, { "dates": "2019-07-04", "c_job": 0 } ]}3v4l.org 上的演示
噜噜哒
我已经使用了旧的和简单的嵌套foreach循环,尽可能简单快捷(代码中的注释)......$template = json_decode('[ { "dates": "2019-07-01", "c_job": 0 }, { "dates": "2019-07-02", "c_job": 0 }, { "dates": "2019-07-03", "c_job": 0 }, { "dates": "2019-07-04", "c_job": 0 } ]', true);$update = json_decode('{ "EXPORT": [ { "dates": "2019-07-01", "c_job": 12 }, { "dates": "2019-07-02", "c_job": 8 }, { "dates": "2019-07-04", "c_job": 11 } ], "IMPORT": [ { "dates": "2019-07-03", "c_job": 11 } ]}', true);和主要代码...// Create blank output array with all entries$output = ["EXPORT" => $template, "IMPORT" => $template];// Loop over update data (from database) - you may need to tweak this for your use caseforeach ( $update as $type => $updateItem ) { // Loop over each set of update values (a row of dates and c_job) foreach ( $updateItem as $updateItem ) { // Locate in empty output array foreach ( $output[$type] as &$item ) { // Same date - update if ( $updateItem['dates'] == $item['dates']) { $item['c_job'] = $updateItem['c_job']; // Stop looking as already updated break; } } }}较短,但涉及更多array_功能,这会创建以日期为键的模板数组,因此您可以使用输入数据中的日期直接更新数据...// Create template array using dates as the array key$template = array_column($template, null, 'dates');$output = ["EXPORT" => $template, "IMPORT" => $template];foreach ( $update as $type => $export ) { foreach ( $export as $export ) { // Use the combination of type (EXPORT) and dates from the update data // to directly update the output (assumes empty value created) $output[$type][$export['dates']]['c_job'] = $export['c_job']; }}// Re-index data to remove dates as keys$output = ["EXPORT" => array_values($output['EXPORT']), "IMPORT" => array_values($output['IMPORT'])];