php - 如何从 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 数据库:无限制 这是产品的测试信息
我想从此输出创建多个变量以获得以下结果,因此我可以在 tpl 文件中使用以下 3 个变量。
$feature = 磁盘空间 $价值 = 100 MB ETC.. 并且 $feature.description = 这是产品的测试信息。
如果这是一个不清楚的问题,请告诉我,我会尝试解决它。
谢谢
解决方案
我确信这可以做得更干净,但它会完成工作:
$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
是格式。
推荐阅读
- r - 在 R 中将格式从数字更改为 POSIXct 对象
- python - 当 wifi 出现故障时,我可以告诉脚本暂停吗?
- google-cloud-platform - 在 GCP 集群上运行 Dask 脚本
- javascript - React 事件处理程序:尝试使用默认值更新购物车数量“onChange”
- apache-spark - Pyspark 更新特征向量中的值
- git - 尝试使用 LFS 将 Unity 文件上传到 git 失败并出现“检测到 GH001 大文件”错误
- angular - nrwl - ng generate 给出超出最大调用堆栈大小
- macos - 用ffmpeg展平两个音轨
- c++ - FFmpeg 在使用奇异分辨率时创建无效输出