PHP获取包含某些值而不是键的数组元素

时间:2018-01-20 07:14:33

标签: php arrays

我找不到相似的这个可能吗?我有一个示例数组

Array
(

    [0] => Array
        (
            [employee_name] => Abegail P.
            [employee_id] => 1297212
            [total_offenses] => 10
            [type] => giveaways
        )

    [2] => Array
        (
            [employee_name] => Carlota
            [employee_id] => 1855076
            [total_offenses] => 5
            [type] => refund
        )

)

我想检索只有赠品类型并且显示如下的数组元素。

Array
    (
        [0] => Array
        (
            [employee_name] => Abegail P.
            [employee_id] => 1297212
            [total_offenses] => 10
            [type] => giveaways
        )
    )

3 个答案:

答案 0 :(得分:1)

您可以使用array_filter

以下是一个例子:

$arr = array
(

    array
        (
            "employee_name" => 'Abegail P.',
            "employee_id" => '1297212',
            "total_offenses" => '10',
            "type" => 'giveaways',
        ),
    array
        (
            "employee_name" => 'Carlota',
            "employee_id" => '1855076',
            "total_offenses" => '5',
            "type" => 'refund',
        )

);


//Use array_filter
$result = array_filter($arr, function($v) {
    //Return if type giveaways
   return $v[ 'type' ] === 'giveaways';
});

echo "<pre>";
print_r( $result );
echo "</pre>";

这将导致:

Array
(
    [0] => Array
        (
            [employee_name] => Abegail P.
            [employee_id] => 1297212
            [total_offenses] => 10
            [type] => giveaways
        )

)

文档:http://php.net/manual/en/function.array-filter.php

答案 1 :(得分:1)

使用array_filter()

$array = array_filter($array, function($value){
    return $value["type"] === "giveaways";
});

答案 2 :(得分:0)

array_filter是完成此任务的完美工具。

$key = giveaways; // I assume this is constant value as
                  // its not writtent as literal or variable.
$new_array = array_filter($array, function( $item ) use( $key ) {
    if (item[type'] == $key ) {
        return true;
    }
    return false;
});