用空数据自动填充数组以匹配另一个数组大小


Autofill array with empty data to match another array size

我有两个数组:

$dates1 = array('9/12','9/13','9/14','9/15','9/16','9/17');
$data1 = array('5','3','7','7','22','18');
// for this dataset, the value on 9/12 is 5
$dates2 = array('9/14','9/15');
$data2 = array('12','1');

你可以看到第二个数据集有更少的日期,所以我需要"自动填充"数组的重置来匹配最大的数据集。

$dates2 = array('9/12','9/13','9/14','9/15','9/16','9/17');
$data2 = array('','','12','1','','');

将有超过2个数据集,所以我必须找到最大的数据集,并为每个较小的数据集运行一个函数来正确格式化它。

我要创建的函数是我的问题。甚至不知道从哪里开始。此外,如果出于某种原因,我可以以不同的方式格式化日期和数据数组(多维数组?)。

您可以使用一些数组函数以非常直接的方式完成此操作。试试这样做:

//make an empty array matching your maximum-sized data set
$empty = array_fill_keys($dates1,'');
//for each array you wish to pad, do this:
//make key/value array
$new = array_combine($dates2,$data2);
//merge, overwriting empty keys with data values
$new = array_merge($empty,$new);
//if you want just the data values again
$data2 = array_values($new);
print_r($data2);

将其转换为函数或将其放入for循环中以操作数组集是非常容易的。我认为,将它们转换为键/值对的关联数组也会使它们更容易使用。

如果数据是相关的,将它们分散到几个数组将是痛苦的。最好的解决方案是用明显的属性名建模对象并与相关的访问器一起使用。

从你的问题中,我没有很多关于什么是数据的提示,然后我不得不猜测一点:

我假设你需要每天记录下载网站的访问情况。而不是使用日期/data1/data2数组,我将建模一个类似的数据结构:

$log = array( 
    array('date'=>'2011-09-12','accessCount'=>7,'downloadCount'=>3),
    array('date'=>'2011-09-13','accessCount'=>9), /* better downloadsCount=>0 though */
    array('date'=>'2011-09-15','accessCount'=>7,'downloadCount'=>3)
    ...
)

使用这个数据结构,我将用add, remove, get, set, search方法建模dayCollection类,所有方法返回一个day实例(是的,删除也是)和相应的签名。day类的每个属性都有标准的getter/setter(你可以解析为魔法方法)。

根据需要操作的数据量,您可以选择只在集合中维护对象数据(在存储时序列化/在检索时反序列化)或整个对象。

由于这个问题缺少关于你的数据模型的细节,所以很难向你展示一些代码。

如果你仍然想填充你的数组,这段代码将是一个很好的开始:

$temp = array($dates, $data1, $data2);
$max = max(array_map('count',$temp));
$result = array_map( function($x) use($max) {
    return array_pad($x,$max,0);
}, $temp);

$result你有你的填充数组。如果你想替换你的数组用一个简单的

list($dates, $data1, $data2) = array_map(....

您应该使用hashmap而不是数组来将每个日期与数据关联。

然后,找到最大的键,用foreach遍历它的键,并测试在小的键中是否存在相同的键。

如果不存在,创建一个空值


用代码编辑(为了完整性,其他答案似乎肯定更好):

$dates_data1 = array('9/12'=>'5', '9/13'=>'3', '9/14'=>'7' /* continued */);
$dates_data2 = array('9/14'=>'12', '9/15'=>'1');
#cycle through each key (date) of the longest array
foreach($dates_data1 as $key => $value){
  #check if the key exists in the smallest and add '' value if it does not
  if(!isset( $date_data2[$key] )){ $date_data2[$key]=''; }
}