仅打印多维数组中包含特定值的行

时间:2014-05-13 19:03:17

标签: php

我在PHP 5.2.3中有这个数组:

$a = array (
    array("a","c","1");
    array("b","a","2");
    array("a","b","3");
    array("b","b","4");
    array("a","a","5");
);

我希望"选择" (或创建一个新数组)只有具有第一个元素" a"的行。像这样:

"a","c","1"
"a","b","3"
"a","a","5"

我该怎么做?

编辑:

<?php
    $a = array (
        array("a","c","1"),
        array("b","a","2"),
        array("a","b","3"),
        array("b","b","4"),
        array("a","a","5"),
    );

    $result = array_filter(
        $array,
        'testFirst'
    );

    print_r($result);
?>

我收到此错误Warning: array_filter() [function.array-filter]: The first argument should be an array in C:\wamp\www\keySearch\test.php on line 13

最终编辑:

<?php
    $a = array (
        array("a","c","1"),
        array("b","a","2"),
        array("a","b","3"),
        array("b","b","4"),
        array("a","a","5"),
    );

    function testFirst($value) {
        return($value[0] == 'a');
    }

    $result = array_filter($a, testFirst);
    print_r($result);
?>

2 个答案:

答案 0 :(得分:4)

function testFirst($value) {
    return($value[0] == 'a');
}

$result = array_filter(
    $a,
    'testFirst'
);

答案 1 :(得分:3)

如果您想手动执行此操作:

$ret = array();
foreach($a as $k => $v)
{
    if ($v[0] == "a")
        $ret[] = $v;
}
print_r($ret);