我有一些关联数组存储字典的词法数据。以下是名为$rowArray
的数组的结构示例:
[2] => Array
(
[\lx] => gunu
[\np] => LH
[\ps] => noun
[\ge] => thick grass in the field, thicket
[\gn] => tshutlha
[\lt] =>
[\va] =>
[\cf] =>
[\ce] =>
[\nt] =>
[\oi] => gunu [LH] thick grass in the field, thicket (noun) (Sets. tshutlha)
)
[3] => Array
(
[\lx] => guru
[\np] => S
[\ps] => noun
[\ge] => ankle
[\gn] => lenyenyana
[\xv0] => ʔam guru-ŋǀı̃
[\xe0] => my ankles
[\lt] =>
[\va] =>
[\cf] =>
[\ce] =>
[\nt] =>
[\oi] => guru [S] ankle (noun) (Sets. lenyenyana) (ex. ʔam guru-ŋǀı̃ ‘my ankles’)
)
我正在创建一个电子表格,我需要创建一行标题,相当于上面数组中的键(例如标题是\ lx \ np \ ps ...)我将这些值存储在一个名为的单独数组中$headArray
。
问题是某些数组的值比其他数组多,因此在创建电子表格时,列未对齐。例如,在上面的[2]
中,有11个值,但在上面的[3]
中,有13个值。因此,在电子表格中,列不会完全匹配。
因此,我首先遍历$rowArray
的所有键以填充$headArray
(这样它将始终具有最大标题数量):
$headArray = array();
foreach($rowArray as $j=>$rA){
foreach($rA as $r=>$a){
if(!in_array($r, $headArray)){
$pos = array_search($r, array_keys($rA));
array_splice($headArray, $pos, 0, $r);
}
}
}
此代码的输出是一个数组,其中所有可能的标题都按正确的顺序排列:
Array
(
[0] => \lx
[1] => \np
[2] => \ps
[3] => \ge
[4] => \gn
[5] => \xv0
[6] => \xe0
[7] => \xv1
[8] => \xe1
[9] => \lt
[10] => \va
[11] => \cf
[12] => \ce
[13] => \nt
[14] => \oi
)
然后我使用此列表($headArray
)来遍历$rowArray
中的所有条目 - 如果$rowArray
中的条目缺少$headArray
的密钥有,然后我把它拼接成空白。实际上,我在电子表格中创建了空白列,因此无论如何都会对齐。要执行此迭代,我使用此代码:
foreach($rowArray as $j=>$rA){
if(count($rA) < count($headArray)){
$rA_keys = array_keys($rA);
$rA_diff = array_diff($headArray, $rA_keys);
foreach($rA_diff as $di=>$ff){
if(!array_key_exists($ff, $rA)){
$rA = array_slice($rA, 0, $di, true) + array($ff => '') + array_slice($rA, $di, NULL, true);
}
}
}
}
此代码的输出如下(与本文中的第一个数组相比):
Array
(
[\lx] => gunu
[\np] => LH
[\ps] => noun
[\ge] => thick grass in the field, thicket
[\gn] => tshutlha
[\xv0] =>
[\xe0] =>
[\xv1] =>
[\xe1] =>
[\lt] =>
[\va] =>
[\cf] =>
[\ce] =>
[\nt] =>
[\oi] => gunu [LH] thick grass in the field, thicket (noun) (Sets. tshutlha)
)
Array
(
[\lx] => guru
[\np] => S
[\ps] => noun
[\ge] => ankle
[\gn] => lenyenyana
[\xv0] => ʔam guru-ŋǀı̃
[\xe0] => my ankles
[\xv1] =>
[\xe1] =>
[\lt] =>
[\va] =>
[\cf] =>
[\ce] =>
[\nt] =>
[\oi] => guru [S] ankle (noun) (Sets. lenyenyana) (ex. ʔam guru-ŋǀı̃ ‘my ankles’)
)
我认为它有效!因此,考虑到所有这些背景知识,我的问题是:
1。在这些foreach
循环之外,即使结果print()
正确,也不会更新数组。就像,当我尝试将数组写入我的电子表格时,没有保存带有拼接和所有内容的更新值。那么我怎样才能使数组在我的foreach
循环中得到更新?
2。做一个逻辑上更有效或更好的方式来做我正在做的事情?这个任务让我头疼了4天,我不确定我的方法是最好的!
答案 0 :(得分:0)
我建议您使用PHPexcel库。我认为你不应该这样做来修改数组并根据最大数组得到标题。我会这样做: