开发者

Converting associative arrays into normal ones

I have an associate array that looks something like this:

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

How can I implode the array into a standard array like this:

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

Or more simply:

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

Does anybody k开发者_运维百科now what I should do?


You can do this:

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

which will give you:

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

Demo


With the function array_merge you can merge arrays.

Example from: 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);
?>

output:

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


Using an associative array:

$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); 

for more information you can read the RecursiveIteratorIterator class

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜