我有一个以这种方式构建的csv文件。它以小时为单位显示了网页浏览量
"00","ARTICLE 1",100
"00","ARTICLE 2",50
"00","ARTICLE 3",30
"01","ARTICLE 1",40
"01","ARTICLE 2",100
"01","ARTICLE 4",200
"02","ARTICLE 1",30
"02","ARTICLE 2",40
"02","ARTICLE 3",30
"03","ARTICLE 5",30
我在我的php代码中导入csv,然后在多维数组中插入内容。当我var_dump我的数组时,这就是我得到的
Array
(
[00] => Array
(
[ARTICLE 1] => 100
[ARTICLE 2] => 50
[ARTICLE 3] => 30
)
[01] => Array
(
[ARTICLE 1] => 40
[ARTICLE 2] => 100
[ARTICLE 4] => 200
)
[02] => Array
(
[ARTICLE 1] => 30
[ARTICLE 2] => 40
[ARTICLE 3] => 30
)
[03] => Array
(
[ARTICLE 5] => 30
)
)
所以我的问题是“第4条”仅在“01”处查看但我希望它出现在键“00”,“02”,“03”中,默认值为0.同样的“第5条“仅出现在关键字”03“。我希望它出现在键“00”,“01”,“02”,“03”,“04”
最后,我希望我的阵列像这样上架
Array
(
[00] => Array
(
[ARTICLE 1] => 100
[ARTICLE 2] => 50
[ARTICLE 3] => 30
[ARTICLE 4] => 0
[ARTICLE 5] => 0
)
[01] => Array
(
[ARTICLE 1] => 40
[ARTICLE 2] => 100
[ARTICLE 3] => 0
[ARTICLE 4] => 200
[ARTICLE 5] => 0
)
[02] => Array
(
[ARTICLE 1] => 30
[ARTICLE 2] => 40
[ARTICLE 3] => 30
[ARTICLE 4] => 0
[ARTICLE 5] => 0
)
[03] => Array
(
[ARTICLE 1] => 0
[ARTICLE 2] => 0
[ARTICLE 3] => 0
[ARTICLE 4] => 0
[ARTICLE 5] => 30
)
)
我尝试过做这样的事情但是没有用
foreach ($orig as $item) {
$new[] = $item;
$new[] = $item;
}
有人可以帮忙吗?
更新
我试过这样的事情
foreach ($articles as $article)
{
$pageviews2[$article] = $pageviews;
}
其中$ pageviews2包含我的csv文件的内容,并且数组文章以这种方式构建
$articles = Array("00", "01", "02", "03","04","05");
以下是我在var_dump $ pageviews2数组
时得到的结果Array
(
[00] => Array
(
[00] => Array
(
[ARTICLE 1] => 100
[ARTICLE 2] => 50
[ARTICLE 3] => 30
)
[01] => Array
(
[ARTICLE 1] => 40
[ARTICLE 2] => 100
[ARTICLE 4] => 200
)
[02] => Array
(
[ARTICLE 1] => 30
[ARTICLE 2] => 40
[ARTICLE 3] => 30
)
[03] => Array
(
[ARTICLE 5] => 30
)
)
[01] => Array
(
[00] => Array
(
[ARTICLE 1] => 100
[ARTICLE 2] => 50
[ARTICLE 3] => 30
)
[01] => Array
(
[ARTICLE 1] => 40
[ARTICLE 2] => 100
[ARTICLE 4] => 200
)
[02] => Array
(
[ARTICLE 1] => 30
[ARTICLE 2] => 40
[ARTICLE 3] => 30
)
[03] => Array
(
[ARTICLE 5] => 30
)
)
答案 0 :(得分:1)
我通常处理这种情况的方式就像你提到的那样,用一组已知值预先填充每个“外部”元素。这可以假设你确切地知道你想要在数组的第二维中有多少元素,并且你提前知道第一维中有多少元素。以下是一些演示代码:
$pageviews = array();
$articles = Array("00", "01", "02", "03");
$prepopulated = Array (
"Article 1" => 0,
"Article 2" => 0,
"Article 3" => 0,
"Article 4" => 0,
"Article 5" => 0
);
然后,您可以在导入csv:
之前创建骨架数组foreach ($articles as $article) {
$pageviews[$article] = $prepopulated;
}
然后,当您从csv导入数据时,您正在执行的所有操作都将覆盖您刚刚创建的框架数组中的默认值:
if (($handle = fopen("pageviews.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$pageviews[$data[0]][$data[1]] = $data[2];
}
fclose($handle);
}