我有这个数组:
Array
(
[0] => Array
(
[0] => 1
[1] => a,b,c
)
[1] => Array
(
[0] => 5
[1] => d,e,f
)
)
我希望最终的数组是这样的:
Array
(
[0] => Array
(
[0] => 1
[1] => a
)
[1] => Array
(
[0] => 1
[1] => b
)
[2] => Array
(
[0] => 1
[1] => c
)
[3] => Array
(
[0] => 5
[1] => d
)
[4] => Array
(
[0] => 5
[1] => e
)
[5] => Array
(
[0] => 5
[1] => f
)
)
这就是我所做的:
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count] = $arr;
$temp[$count][1] = $row;
$count++;
}
}
print_r($temp);
?>
这完全有效,但我想知道是否有更好的方法来做到这一点。当我有大量数据时,这可能会非常慢。
答案 0 :(得分:1)
尝试这样......
library(dplyr)
data(iris)
df <- iris %>%
group_by(Species) %>%
mutate(RankSepal = percent_rank(Sepal.Length),
RankPetal = percent_rank(Petal.Length))
答案 1 :(得分:1)
这是一种功能性方法:
$result = array_merge(...array_map(function(array $a) {
return array_map(function($x) use ($a) {
return [$a[0], $x];
}, explode(",", $a[1]));
}, $array));
或者仅仅使用两个循环:
$result = [];
foreach ($array as $a) {
foreach (explode(",", $a[1]) as $x) {
$result[] = [$a[0], $x];
}
}
这些时间显示简单的循环结构快了〜8倍。
4.06s user 0.08s system 99% cpu 4.160 total
0.53s user 0.05s system 102% cpu 0.561 total
答案 2 :(得分:0)
如果您需要其他方法,
$array = array(array(1, "a,b,c"), array(5, "d,e,f"));
$temp = [];
array_walk($array, function ($item, $key) use (&$temp) {
$second = explode(',', $item[1]);
foreach ($second as $v) {
$temp[] = [$item[0], $v];
}
});
print_r($temp);
array_walk - 将用户提供的函数应用于数组的每个成员
以下是demo。