2017-02-28 113 views
0

我想在php中創建一個函數,將3個字符串轉換爲多維數組中的一個元素。所以此刻的數組是這樣的:在PHP中將字符串名轉換爲變量?

`$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)轉換爲變量名稱。任何幫助將非常感激!

+0

首先,不這樣做......有太多的東西可以用這種方式出錯...方式太多..如果你堅持這樣做,使用提取功能http://php.net/manual/en/function.extract.php – Dimi

回答

0

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