Reputation: 1737
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
)
)
Upvotes: 0
Views: 64
Reputation: 26844
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
Upvotes: 1
Reputation: 5405
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;
});
Upvotes: 0
Reputation: 9853
use array_filter()
$array = array_filter($array, function($value){
return $value["type"] === "giveaways";
});
Upvotes: 1