簡體   English   中英

將字符串名稱轉換為PHP中的變量?

[英]Convert string name into variable in php?

我正在嘗試在php中創建一個函數,該函數會將3個字符串轉換為多維數組中的元素。 所以目前的數組是這樣的:

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

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

];'   

我正在嘗試通過表單將其添加到其中:

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

];`

因此,用戶輸入了“智能手機”,“ htc one”和300。我創建了以下功能:

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

但是我似乎無法將字符串($ newitemvariable)轉換為變量名。 任何幫助將非常感激!

除非這樣做相當冒險且不專業,所以使用的正確函數是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