php - 如何根据php中的字段过滤数组?
问题描述
我有一个如下所示的 php 代码:
$category = get_the_category();
//Line #A
echo '<pre>'; print_r($category); echo '</pre>';
//Line #B
第 2 行的代码返回以下数组;
Array
(
[0] => WP_Term Object
(
[term_id] => 13085
[name] => Cannabis
[slug] => democracy_project_cannabis
[term_group] => 0
[term_taxonomy_id] => 13085
[taxonomy] => category
[description] => Hello World
[parent] => 13083
[count] => 8
[filter] => raw
[cat_ID] => 13085
[category_count] => 8
[category_description] => Good Morning
[cat_name] => Cannabis
[category_nicename] => democracy_project_cannabis
[category_parent] => 13083
)
[1] => WP_Term Object
(
[term_id] => 13093
[name] => Today
[slug] => today
[term_group] => 0
[term_taxonomy_id] => 13093
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 3
[filter] => raw
[cat_ID] => 13093
[category_count] => 3
[category_description] =>
[cat_name] => Today
[category_nicename] => today
[category_parent] => 0
)
)
问题陈述:
我想知道我需要编写什么 php 代码,以便它根据[name] => Today过滤数组。它应该只需要一个字段,即[name] => Today
我想我需要使用array_filter()
方法,但我不确定如何使用它。
解决方案
使用array_filter()
and use
,您将在按值过滤多维数组时获得更大的灵活性
$filterBy = 'Today'; // any index value you want
$expected = array_filter($cats, function ($var) use ($filterBy) {
return ($var->name == $filterBy);
});
print_r($expected);
推荐阅读
- python - 更改根文件中的分支名称
- node.js - 我的 BigQuery 查询中的条件语句被忽略
- php - PHP - 组合不同长度的数组
- batch-file - 批处理文件问题。它是一个错误吗?
- sql - 如何计算前 X% 的观看者观看了 50% 的观看次数
- regex - 根据第一个目录重定向
- python - 如何在 python 中使用配置文件组织单元测试?
- angular - 如何在 mat-table Angular 9 的每一行中添加一个按钮?
- python - 使用 pyodbc 连接到 microsoft sql db
- android - 需要alarmManager 或workManager?