从多维数组我想提取单列

时间:2014-12-12 12:42:37

标签: php arrays multidimensional-array

输入:

Array
(
[1] => Array
    (
        [id] => 11
        [has_point] => 0
        [xpr] => 0
        [war] => 0
        [sty] => 0
    )

[2] => Array
    (
        [id] => 52
        [has_point] => 0
        [xpr] => 0
        [war] => 0
        [sty] => 0
    )

[3] => Array
    (
        [id] => 34
        [has_point] => 1
        [xpr] => 300
        [war] => 0
        [sty] => 0
    )

[4] => Array
    (
        [id] => 47
        [has_point] => 0
        [xpr] => 0
        [war] => 0
        [sty] => 0
    )

[5] => Array
    (
        [id] => 57
        [has_point] => 1
        [xpr] => 500
        [war] => 0
        [sty] => 0
    )

输出:

Array
(
    [1] => 11
    [2] => 52
    [3] => 34
    [4] => 47
    [5] => 57
)

因此PHP中有任何函数可以获取此输出,所以我不必自己编写。

我试过

function customArraySearch($array, $search) {
    $col = array();
    foreach ($array as $v) {
        $col[] = $v[$search];
    }
    return $col;
}

我正在获取输出但是我想优化我的代码,所以如果数组中有10000条记录则需要一些时间。请建议任何内置的php函数

2 个答案:

答案 0 :(得分:6)

您需要的功能是 array_column

$id_array = array_column($your_array, 'id');

注意:支持的版本 PHP 5> = 5.5.0

答案 1 :(得分:0)

试试这个......

 $aa = array(
    array(11, 0,0,0,0),
    array(52, 0,0,0,0),
    array(34, 0,0,0,0),
    array(47, 0,0,0,0),
    array(57, 0,0,0,0)

    );

     $newarray=array();
    foreach( $aa as $k => list($a, $b,$c,$d,$e)) {
    $newarray[]=$a;
    }
    print_r($newarray);

支持的版本为(PHP 5> = 5.5.0)