Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

php - How to get array of values from an associative arrays?

How can I get an array of values from an associative array ?

Associate array Example:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )
    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )
    [2] => Array
        (
            [0] => 7
        )
)

Desired Output

Array
(1,2,3,4,5,6,7)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not sure it'll suit you, as it's PHP >= 5.3 only, but here's a possible solution, using array_walk_recursive and a closure (see Anonymous functions) :

$array = array(
    array(1, 2, 3), 
    array(4, 5, 6), 
    array(7), 
);

$result = array();
array_walk_recursive($array, function ($value, $key) use (& $result) {
    $result[] = $value;
});
var_dump($result);

And the result :

array
  0 => int 1
  1 => int 2
  2 => int 3
  3 => int 4
  4 => int 5
  5 => int 6
  6 => int 7

Basicaly, the closure is the only way I got this to work : it's used to import the $result variable, by reference, into the anonymous function.



And, just to post it, the only I got this working for PHP 5.2 (i.e. not using a closure) is with this :

$result = array();
array_walk_recursive($array, 'my_func', & $result);
var_dump($result);

function my_func($value, $key, & $result) {
    $result[] = $value;
}

Which works too -- but raises a warning :

Deprecated: Call-time pass-by-reference has been deprecated

Unfortunatly, I didn't find a way of getting this to work without passing $result by reference at call-time :-(
(Maybe someone else has an idea, about how to do that ?)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...