繁体   English   中英

在数组中插入 php 变量

[英]Insert php variable inside array

我有一个 CPT 过滤器,我需要在 array() 中手动键入所有自定义分类名称:

sc_render_filter(
      'test',
      'All Categories',
      array( 'Category One', 'Category two', 'Category three'),
      ''
      . ($current_sub_brand ? ( 'sub_brand=' . $current_sub_brand . '&' ) : '' )
      . ($current_varietal ? ( 'varietal=' . $current_varietal . '&' ) : '' )
      . ($current_publication ? ( 'publication=' . $current_publication . '&' ) : '' )
      . ($current_vintage ? ( 'vintage=' . $current_vintage . '&' ) : '' )
    );

是否有可能以某种方式使用 array() 中的变量或 foreach 循环来自动生成术语或名称? 或者也许我需要另一种方法? 这就是我在 foreach 中所拥有的:

$source = '';
    foreach ($termslist as $term) { 
        $source .= "'". $term->name. "'". ',';
    }
    echo rtrim($source, ',');

不幸的是,对于您的项目,使用可变变量是合适的(我通常不认可)。 使用变量变量是数组数据未正确存储的症状。 您拥有单独的$current_变量这一事实似乎是一个更早需要解决的问题。

同时,您可以遍历已知键并动态访问这些变量。 完成后,调用http_build_query()干净、可靠地生成 url 查询字符串字符串。

代码:(演示

$keys = ['sub_brand', 'varietal', 'publication', 'vintage'];
$data = [];
foreach ($keys as $key) {
    $data[$key] = ${'current_' . $key};
}
$queryString = http_build_query($data);

sc_render_filter(
    'test',
    'All Categories',
    ['Category One', 'Category two', 'Category three'],
    $queryString
);

查询字符串字符串如下所示:

sub_brand=foo&varietal=bar&publication=boo&vintage=far

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM