我正在尝试在 PHP 中加载 CSV。
我有一个 CSV 文件,有 3 列,简单的值。
我设法能够遍历每一行并输出每个值,但我需要根据唯一值和行中的某个位置有条件地获取数据。
例如,对于 a 列中的每个唯一值,我需要根据 b 列的值生成一个数据对象数组,使用 c 列作为其中一个值的条件。
我的 CSV:
1 123 0
1 124 0
1 125 0
1 126 0
1 127 0
1 128 0
1 129 0
1 130 1
1 131 1
1 132 1
1 133 1
1 134 1
1 135 1
2 123 0
2 124 0
2 125 0
2 126 1
2 127 1
2 128 1
2 129 1
2 130 1
2 131 1
2 132 1
2 133 1
2 134 1
2 135 1
3 256 0
3 456 0
3 321 0
3 489 0
3 965 0
3 652 1
3 741 1
我用来询问的代码:
<?php
$stack = array();
if (($han = fopen("sample.csv", "r")) !== FALSE) {
while (($data = fgetcsv($han, 50, ",")) !== FALSE) {
array_push($stack, $data); //push each arr1 into arr2(stack)
}
fclose($han);
}
sort($stack); //sort arr2
$newarray = array();
foreach($stack as $val){
$lineid = $val[0];
$segmentid = $val[1];
$action = $val[2];
$newarray[$lineid][$segmentid] = $action;
}
print_r($newarray);
?>
输出
Array
(
[1] => Array
(
[123] => 0
[124] => 0
[125] => 0
[126] => 0
[127] => 0
[128] => 0
[129] => 0
[130] => 1
[131] => 1
[132] => 1
[133] => 1
[134] => 1
[135] => 1
)
[2] => Array
(
[123] => 0
[124] => 0
[125] => 0
[126] => 1
[127] => 1
[128] => 1
[129] => 1
[130] => 1
[131] => 1
[132] => 1
[133] => 1
[134] => 1
[135] => 1
)
[3] => Array
(
[256] => 0
[321] => 0
[456] => 0
[489] => 0
[652] => 1
[741] => 1
[965] => 0
)
)
我想要实现的伪代码
for each unique column_a value {
grab all column_b's within this unique column_a and for each
$column_b_object = new stdClass;
$column_b_object->id = $column_b_value;
if (column_c_value = "0") {
$column_b_object->zero = "no";
}
$column_bs[] = $column_b_object;
execute something, reset, move to next unique column_a
}
编辑解决方案:
<?php
$stack = array();
if (($han = fopen("sample.csv", "r")) !== FALSE) {
while (($data = fgetcsv($han, 50, ",")) !== FALSE) {
array_push($stack, $data); //push each arr1 into arr2(stack)
}
fclose($han);
}
sort($stack); //sort arr2
$newarray = array();
foreach($stack as $val){
$lineid = $val[0]; $segmentid = $val[1]; $action = $val[2];
$newarray[$lineid][$segmentid] = $action;
}
foreach($newarray as $value) {
foreach($value as $key => $value2){
echo $key . " | " . $value2 . "<br />";
}
echo "STOP";
}
?>
希望这是有道理的。
谢谢