简体   繁体   English

将字符串名称转换为PHP中的变量?

[英]Convert string name into variable in php?

I'm trying to create a function in php that will convert 3 strings into an element in a multidimensional array. 我正在尝试在php中创建一个函数,该函数会将3个字符串转换为多维数组中的元素。 So the array at the moment is this: 所以目前的数组是这样的:

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

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

];'   

And I'm trying to add this element to it through a form: 我正在尝试通过表单将其添加到其中:

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

];`

So the user inputs 'smartphone,'htc one', and 300. I've created this function: 因此,用户输入了“智能手机”,“ htc one”和300。我创建了以下功能:

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

But I cannot seem to convert the string ($newitemvariable) into the variable name. 但是我似乎无法将字符串($ newitemvariable)转换为变量名。 Any help would be much appreciated! 任何帮助将非常感激!

Except it is quite risky and not professional to do so the right function to use is eval(): 除非这样做相当冒险且不专业,所以使用的正确函数是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 > 

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

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