1

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;

2 Answers 2

2

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.

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

Comments

1

You can use loop:

$travelbudget = [];
foreach ($costdata as $arr) {
    if ($arr['cost_category'] === "Travel") {
        $travelbudget[] = $arr;
    }
}

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.