如何“变平"一个多维数组到 PHP 中的简单数组?
这可能是初学者的问题,但我已经阅读了较长时间的文档,但找不到任何解决方案.我想我可以对每个维度使用 implode,然后将这些字符串与 str_split
重新组合在一起以创建新的简单数组.但是我永远不知道连接模式是否也在值中,所以在执行 str_split
之后,我的原始值可能会中断.
It's probably beginner question but I'm going through documentation for longer time already and I can't find any solution. I thought I could use implode for each dimension and then put those strings back together with str_split
to make new simple array. However I never know if the join pattern isn't also in values and so after doing str_split
my original values could break.
对于多维数组内部的数组,是否有类似 combine($array1, $array2)
的东西?
Is there something like combine($array1, $array2)
for arrays inside of multi-dimensional array?
推荐答案
使用array_walk_recursive
<?php
$aNonFlat = array(
1,
2,
array(
3,
4,
5,
array(
6,
7
),
8,
9,
),
10,
11
);
$objTmp = (object) array('aFlat' => array());
array_walk_recursive($aNonFlat, create_function('&$v, $k, &$t', '$t->aFlat[] = $v;'), $objTmp);
var_dump($objTmp->aFlat);
/*
array(11) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
[5]=>
int(6)
[6]=>
int(7)
[7]=>
int(8)
[8]=>
int(9)
[9]=>
int(10)
[10]=>
int(11)
}
*/
?>
使用 PHP 5.5.9-1ubuntu4.24 (cli) 测试(构建时间:2018 年 3 月 16 日 12:32:06)
Tested with PHP 5.5.9-1ubuntu4.24 (cli) (built: Mar 16 2018 12:32:06)
相关文章