如何从关联数组中获取值数组? [英] How to get array of values from an associative arrays?

查看:76
本文介绍了如何从关联数组中获取值数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从关联数组中获取值数组?

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

关联数组示例:

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

所需的输出

Array
(1,2,3,4,5,6,7)

推荐答案

不确定是否适合您,因为它仅适用于PHP> = 5.3,但这是一种可行的解决方案,使用匿名函数):

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

结果:

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

基本来说,闭包是使它起作用的唯一方法:它用于通过引用将$result变量导入到匿名函数中.

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.


而且,为了发布它,我唯一可以在PHP 5.2 上运行的工具(即不使用闭包)就是这样的:

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

不幸的是,我没有找到一种方法来在呼叫时不通过引用传递$result的情况下使它起作用:-(
(也许其他人对此有一个想法吗?)

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 ?)

这篇关于如何从关联数组中获取值数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆