1 回答
TA贡献1852条经验 获得超1个赞
以下代码创建一个模板数组,以便每个记录包含所有值,然后用于array_merge()将每个记录中的值复制到模板中。任何不在记录中的值都将保留为空,以确保保持对齐(代码注释中有更多描述)...
// Start with the column list and split into an array
$headers = explode(',', 'distinguishedname,o,objectclass,dc,sn,uid,mail,cn');
// Create template record with the fields you want to end up with
$header = array_fill_keys($headers, null);
$output = [];
foreach ( $details as $detail ) {
foreach ( $detail as $name => $entry ) {
// Set the values in the template header from the current entry
$newEntry = array_merge( $header, $entry );
// Add the name in
$newEntry ['distinguishedname'] = $name;
// Process the object class from an array to a string
$newEntry ['objectclass'] = "{".implode(",", $newEntry ['objectclass'])."}";
$output [] = $newEntry;
}
}
// Write file out
$fh = fopen("ad.csv", "w");
fputcsv($fh, $headers);
foreach ( $output as $row ) {
fputcsv($fh, $row);
}
fclose($fh);
样本数据给出......
distinguishedname,o,objectclass,dc,sn,uid,mail,cn
"dc=example,dc=com",example.com,"{simpleSecurityObject,dcObject,organization}",example,,,,
"uid=newton,dc=example,dc=com",,"{simpleSecurityObject,dcObject,organization}",,Newton,Newton,newton@ldap.forumsys.com,"Isaac Newton"
请注意,使用的fpustcsv()优点是,如果字段包含逗号(分隔符),那么它会将它们放在引号中以确保它们只是一个字段。
编辑:
$headers = explode(',', 'distinguishedname,o,objectclass,dc,sn,uid,mail,cn');
$output = [];
foreach ( $details as $name => $entry ) {
echo $name.PHP_EOL;
$newEntry = [];
foreach ( $headers as $header ) {
$value = $entry[$header] ?? null;
if ( is_array($value) ) {
$value = "{".implode(",", $value)."}";
}
$newEntry [$header] = $value;
}
$newEntry ['distinguishedname'] = $name;
$output [] = $newEntry;
}
- 1 回答
- 0 关注
- 102 浏览
添加回答
举报