簡體   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