在WordPress中如何筛选二维数组并获取option_name的值
在WordPress中筛选二维数组并获取指定option_name对应值的方法
先把你提供的数组整理成标准PHP格式:
$options_array = array( array( 'option_id' => 4638, 'option_name' => 'custom plugin chatbot checkbox', 'option value' => 'on', 'autoload' => 'yes' ) );
给你两种实用的处理方式:
方式一:手动循环遍历筛选
直接遍历数组,匹配目标option_name后取出对应值,逻辑简单直观:
$target_name = 'custom plugin chatbot checkbox'; $target_value = ''; foreach ($options_array as $item) { // 先判断键存在避免报错,再匹配名称 if (isset($item['option_name']) && $item['option_name'] === $target_name) { $target_value = $item['option value']; break; // 找到后立刻停止循环,节省资源 } } // 输出结果,这里会打印'on' echo $target_value;
方式二:用WordPress内置函数组合处理
利用array_filter筛选符合条件的子数组,再用wp_list_pluck提取对应字段值,更贴合WordPress开发习惯:
$target_name = 'custom plugin chatbot checkbox'; // 筛选出匹配option_name的子数组 $filtered_items = array_filter($options_array, function($item) use ($target_name) { return isset($item['option_name']) && $item['option_name'] === $target_name; }); // 提取对应的值,取筛选结果的第一个 $value_list = wp_list_pluck($filtered_items, 'option value'); $target_value = !empty($value_list) ? reset($value_list) : ''; echo $target_value;
额外提示
如果这个数组是从WordPress的wp_options表查出来的,其实没必要手动处理数组——直接用WordPress自带的get_option()函数更方便:
$target_value = get_option('custom plugin chatbot checkbox'); echo $target_value; // 同样输出'on'
内容的提问来源于stack exchange,提问作者Rashmi Pani
相关产品推荐
相关产品推荐

