首页 > 解决方案 > 如何从 PHP 或 smarty 中的单个变量输出创建多个变量?

问题描述

php代码。

    public function GetProduct($id, $bc = '')
{
    $productname = WHMCS\Product\Product::getProductName($id);
    $description = WHMCS\Product\Product::getProductDescription($id);
    $details = WHMCS\Product\Product::find($id);
    $pricing = $details->pricing();
    if ($bc == '') {
        $price = $pricing->first();
    } else {
        $price = $pricing->byCycle($bc);
        if (is_null($price)) {
            $price = $pricing->first();
        }
    }
    return array(
        'name' => $productname,
        'description' => $description,
        'price' => $price,
    );
}

当我在 tpl 文件中使用 {$description} 变量时的输出。

磁盘空间:1000 MB
带宽:10,000 MB
电子邮件帐户:25
子域:100
MySql 数据库:无限制

这是产品的测试信息

来自 phpMyAdmin 的屏幕截图

我想从此输出创建多个变量以获得以下结果,因此我可以在 tpl 文件中使用以下 3 个变量。

$feature = 磁盘空间
$价值 = 100 MB

ETC..

并且
$feature.description = 这是产品的测试信息。

如果这是一个不清楚的问题,请告诉我,我会尝试解决它。

谢谢

标签: phpsmartywhmcs

解决方案


我确信这可以做得更干净,但它会完成工作:

$description = "Disk Space: 1000 MB
Bandwidth: 10,000 MB
Email Accounts: 25
Subdomains: 100
MySql DataBase: UNLIMITED

This is test information for products,
with a multiline description";

$descArr = explode("\r\n", $description);
$lineCount = 1;
$desc = "";
foreach ($descArr as $line)
{
    if ($lineCount <= 5)
    {
        list($key, $val) = explode(":", $line);
        $val = trim($val);
        echo "key: [" . $key . "] \n";
        echo "val: [" . $val . "] \n\n";
    }
    else
    {
        $desc .= $line . "\n";
    }
    $lineCount++;
}

echo "desc:" . $desc . "\n";

输出:

key: [Disk Space]
val: [1000 MB]

key: [Bandwidth]
val: [10,000 MB]

key: [Email Accounts]
val: [25]

key: [Subdomains]
val: [100]

key: [MySql DataBase]
val: [UNLIMITED]

desc:
This is test information for products,
with a multiline description

我刚刚echo取出了键/值对。当然,您可以将它们存储到变量中。


如果您希望将 key/val 对存储在变量中:

$description = "Disk Space: 1000 MB
Bandwidth: 10,000 MB
Email Accounts: 25
Subdomains: 100
MySql DataBase: UNLIMITED

This is test information for products,
with a multiline description";

$descArr = explode("\r\n", $description);

$keys = $vals = [];
$lineCount = 0;
$desc = "";

foreach ($descArr as $line)
{
    if ($lineCount < 5)
    {
        list($key, $val) = explode(":", $line);
        $val = trim($val);
        $keys[$lineCount] = $key;
        $vals[$lineCount] = $val;
    }
    else
    {
        $desc .= $line . "\n";
    }
    $lineCount++;
}

var_dump($keys); 
var_dump($vals); 
echo "desc:" . $desc . "\n";

输出:

array(5) {
  [0]=>
  string(10) "Disk Space"
  [1]=>
  string(9) "Bandwidth"
  [2]=>
  string(14) "Email Accounts"
  [3]=>
  string(10) "Subdomains"
  [4]=>
  string(14) "MySql DataBase"
}
array(5) {
  [0]=>
  string(7) "1000 MB"
  [1]=>
  string(9) "10,000 MB"
  [2]=>
  string(2) "25"
  [3]=>
  string(3) "100"
  [4]=>
  string(9) "UNLIMITED"
}
desc:
This is test information for products,
with a multiline description

$keys&$vals是并行数组。这一切都基于顶部的五行格式,$description其中key:value是格式。


推荐阅读