在Array中搜索并获取特定的字符串值

时间:2018-01-15 15:28:26

标签: php arrays wordpress

我有一个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);

我想做的是让所有'cost_amount' 'cost_category'$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; "旅行"

这是我迄今为止所做的。我得到一个空白值。没错。

{{1}}

2 个答案:

答案 0 :(得分:2)

而不是array_search,您应该使用array_filterarray_search只返回它找到的第一个与你的针相等的元素。 array_filter将返回数组中的所有条目,函数返回true

$found_Travel = array_filter($listtravelcost, function($entry)  {
    return $entry['cost_category'] === 'Travel';
});

其余代码应该有效。

答案 1 :(得分:1)

你可以使用循环:

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