我有一个多级数组
$array = array("14529" => array("900" => array("87" => array() ) ) );
print_r(array_keys($array)); // result array("14529");
如何将此数组合并到单个数组
$array = array("14529", "900", "87");
答案 0 :(得分:3)
这是一个可以完成你想要的功能。它以递归方式完成,因此数组的深度无关紧要。
function mergeArrayMultiKeyToSingleArray($array, $result=[])
{
foreach($array as $key => $value) {
$result[] = $key;
if(is_array($value)) {
$result = mergeArrayMultiKeyToSingleArray($value, $result);
}
}
return $result;
}
// USAGE:
$array = array("14529" => array("900" => array("87" => array() ) ) );
$array = mergeArrayMultiKeyToSingleArray($array);
// $array is now ["14529", "900", "87"]
答案 1 :(得分:1)
使用RecursiveIteratorIterator类的解决方案:
$arr = ["14529" => ["900" => ["87" => [] ] ] ];
$keys = [];
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($arr), RecursiveIteratorIterator::SELF_FIRST) as $k => $v) {
$keys[] = $k;
}
print_r($keys);
输出:
Array
(
[0] => 14529
[1] => 900
[2] => 87
)
答案 2 :(得分:0)
我是使用类
完成的Pipeline
class ArrayStripper
{
private $items = [];
public function strip($arrayOrItem)
{
if(is_array($arrayOrItem))
{
foreach ($arrayOrItem as $item)
{
$this->strip($item);
}
}
else
{
$this->items[] = $arrayOrItem;
}
}
public function get()
{
return $this->items;
}
}