【问题标题】:Convert string name into variable in php?将字符串名称转换为php中的变量?
【发布时间】:2017-07-19 16:32:12
【问题描述】:

我正在尝试在 php 中创建一个函数,它将 3 个字符串转换为多维数组中的一个元素。所以此刻的数组是这样的:

`$testcart=[$testcamera = [
'name' => 'Sony camera',
'price' => 170
   ]
    ];

$phone = [
    'name' => 'Lg g3',
    'price' => 400

];'   

我正在尝试通过表单将此元素添加到其中:

    `$smartphone = [
    'name' => 'HTC One',
    'price' => 300

];`

所以用户输入'smartphone、'htc one'和300。我创建了这个函数:

function newcreate_item($newitemvariable,$newitemname,$newitemprice) {
    $newitem = "$" . $newitemvariable;
    $newitem = [
    'name' =>$newitemname,
    'price' =>$newitemprice];
     return $newitem; 
}

但我似乎无法将字符串 ($newitemvariable) 转换为变量名。任何帮助将不胜感激!

【问题讨论】:

标签: php arrays function variables multidimensional-array


【解决方案1】:

除非这样做非常冒险且不专业,否则正确使用的函数是 eval():

php -a
Interactive mode enabled

php > $str = '$testcart=[
php ' [
php ' \'name\' => \'Sony camera\',
php ' \'price\' => 170
php ' ],
php ' [
php '     \'name\' => \'Lg g3\',
php '     \'price\' => 400
php ' 
php ' ]];';
php > eval($str);
php > var_dump($testcart);
array(2) {
  [0]=>
  array(2) {
    ["name"]=>
    string(11) "Sony camera"
    ["price"]=>
    int(170)
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(5) "Lg g3"
    ["price"]=>
    int(400)
  }
}
php > 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 2016-11-20
    • 2015-10-27
    • 2018-02-14
    • 2011-08-27
    • 2010-12-04
    相关资源
    最近更新 更多