I have a Wordpress post meta that has multiple arrays like this.
我有一个Wordpress post meta,它有多个像这样的数组。
$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"
我想要做的是获得所有'cost_amount',其中'cost_category'是“旅行”
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
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
.
您应该使用array_filter而不是array_search。 array_search只返回它找到的第一个与你的针相等的元素。 array_filter将返回数组中的所有条目,函数返回true。
$found_Travel = array_filter($listtravelcost, function($entry) {
return $entry['cost_category'] === 'Travel';
});
The rest of your code should work.
其余代码应该可以工作。
1
You can use loop:
你可以使用循环:
$travelbudget = [];
foreach ($costdata as $arr) {
if ($arr['cost_category'] === "Travel") {
$travelbudget[] = $arr;
}
}
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2018/01/15/e8dab60fb8f35806292178f570486a9f.html。