0

I Can't find similar to this is this possible? I have an example array

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
        )

)

I want to retrieve array elements that has only have a giveaway types and display like this.

Array
    (
        [0] => Array
        (
            [employee_name] => Abegail P.
            [employee_id] => 1297212
            [total_offenses] => 10
            [type] => giveaways
        )
    )
2
  • I just wonder if you accept any of those four solution... They did a lot of effort to provide you working results even with the live demo. Go and click on Accept the solution.. stackoverflow.com/tour Commented Jan 20, 2018 at 8:12
  • All answers have point they all correct for me Commented Jan 21, 2018 at 13:15

3 Answers 3

1

You can use array_filter

Here is an example:

$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>";

This will result to:

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

)

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

Sign up to request clarification or add additional context in comments.

Comments

1

use array_filter()

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

Comments

0

array_filter is the perfect tool for doing that.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.