简体   繁体   English

在数组中插入 php 变量

[英]Insert php variable inside array

I have a filter for the CPT and I need to manually type all custom taxonomy names inside the 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 . '&' ) : '' )
    );

Is it possible somehow to use the variable or foreach loop inside array() to automatically generate terms or names?是否有可能以某种方式使用 array() 中的变量或 foreach 循环来自动生成术语或名称? Or maybe I need another approach?或者也许我需要另一种方法? This is what I have in foreach:这就是我在 foreach 中所拥有的:

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

Unfortuntely for your project, it is appropriate to use variable variables (which I do not typically endorse).不幸的是,对于您的项目,使用可变变量是合适的(我通常不认可)。 Using variable variables is a symptom that array data is not properly stored as such.使用变量变量是数组数据未正确存储的症状。 The fact that you have individual $current_ variables looks to be an earlier problem to address.您拥有单独的$current_变量这一事实似乎是一个更早需要解决的问题。

In the meantime, you can loop through the know keys and dynamically access these variables.同时,您可以遍历已知键并动态访问这些变量。 When finished, call http_build_query() to cleanly, reliably generate a url querystring string.完成后,调用http_build_query()干净、可靠地生成 url 查询字符串字符串。

Code: ( Demo )代码:(演示

$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
);

The querystring string looks like this:查询字符串字符串如下所示:

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

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

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