Reputation: 13
I have a Wordpress post meta that has multiple arrays like this.
$costdata = Array(
Array( 'cost_id' => 1, 'cost_category' => 'Travel', 'cost_amount' => '3540')
Array( 'cost_id' => 2, 'cost_category' => 'Materials', 'cost_amount' => '1644')
Array( 'cost_id' => 3, 'cost_category' => 'Travel', 'cost_amount' => '1800')
);
add_post_meta($project_id, 'costdata', $costdata);
What I want to do is to get all 'cost_amount'
where 'cost_category'
is "Travel"
This is what I've done so far. I get a blank value. No error.
$listtravelcost = get_post_meta($project_id, 'costdata');
/*Calculate Travel cost */
$found_Travel = array_search('Travel', array_column($listtravelcost, 'cost_category'));
$travelbudget = array_column($found_Travel, 'cost_amount');
$printtravelbudget = array_sum($travelbudget);
echo $printtravelbudget;
Upvotes: 1
Views: 58
Reputation: 2505
Instead of array_search
, you should use array_filter
. array_search
will only return the first element it finds that is equal to your needle. array_filter
will return all entries in an array, for which the function returns true
.
$found_Travel = array_filter($listtravelcost, function($entry) {
return $entry['cost_category'] === 'Travel';
});
The rest of your code should work.
Upvotes: 2
Reputation: 1391
You can use loop:
$travelbudget = [];
foreach ($costdata as $arr) {
if ($arr['cost_category'] === "Travel") {
$travelbudget[] = $arr;
}
}
Upvotes: 1