将关联数组转换为普通数组

时间:2011-10-08 12:53:05

标签: php arrays associative-array

我有一个看起来像这样的关联数组:

array
(
   'device_1' => array('a','b','c','d'),
   'device_2' => array('x','y','z')
)

如何将数组内爆成这样的标准数组:

array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'x', 5 => 'y', 6 => 'z')

或更简单:

array('a','b','c','d','e','x','y','z')

有人知道我应该做什么吗?

3 个答案:

答案 0 :(得分:4)

你可以这样做:

$result = call_user_func_array('array_merge', $array);

会给你:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => x
    [5] => y
    [6] => z
)

Demo

答案 1 :(得分:1)

使用函数array_merge可以合并数组。

示例来自: http://www.php.net/manual/en/function.array-merge.php

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

输出:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

答案 2 :(得分:0)

使用关联数组:

$devices = array
(
   'device_1' => array('a','b','c','d'),
   'device_2' => array('x','y','z')
);

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($devices));
foreach( $iterator as $value ) {
    $output[] = $value;
}

print_r($output); 

有关详情,请阅读RecursiveIteratorIterator class