是否存在从多维数组中交换值的函数。
我有一个看起来像这样的数组
$bad[] = array('100','200','300');
$bad[] = array('ENGLISH 100','ENGLISH 200','ENGLISH 300');
$bad[] = array('GERMAN 100','GERMAN 200','GERMAN 300');
但是,我希望它看起来像这样
$good[] = array('100','ENGLISH 100','GERMAN 100');
$good[] = array('200','ENGLISH 200','GERMAN 200');
$good[] = array('300','ENGLISH 300','GERMAN 300');
答案 0 :(得分:2)
这应该这样做:
$bad[] = array('100','200','300');
$bad[] = array('ENGLISH 100','ENGLISH 200','ENGLISH 300');
$bad[] = array('GERMAN 100','GERMAN 200','GERMAN 300');
for ($i=0; $i < count($bad[0]); $i++) {
$good[$i] = array(
$bad[0][$i],
$bad[1][$i],
$bad[2][$i],
);
}
结果:
array (
0 => array (0 => '100', 1 => 'ENGLISH 100', 2 => 'GERMAN 100', ),
1 => array (0 => '200', 1 => 'ENGLISH 200', 2 => 'GERMAN 200', ),
2 => array (0 => '300', 1 => 'ENGLISH 300', 2 => 'GERMAN 300', ),
)
答案 1 :(得分:0)
Tjoene提供了一个非常干净的解决方案,我非常喜欢,因为它的线性。但是,如果数据集未知,我会考虑以下示例,并可用于执行基于键的操作。
$bad[0] = array('100','200','300');
$bad[1] = array('ENGLISH 100','ENGLISH 200','ENGLISH 300');
$bad[2] = array('GERMAN 100','GERMAN 200','GERMAN 300');
$good = array();
foreach ($bad as $k => $v) {
if($k == 0)
continue;
foreach ($v as $key => $value) {
$res = explode(' ', $value);
$good[$res[1]][] = $res[0];
}
}
输出
Array
(
[100] => Array ([0] => ENGLISH [1] => GERMAN )
[200] => Array ([0] => ENGLISH [1] => GERMAN )
[300] => Array ([0] => ENGLISH [1] => GERMAN )
)