I'm trying to create a function in php that will convert 3 strings into an element in a multidimensional array. 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:
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. Any help would be much appreciated!
Except it is quite risky and not professional to do so the right function to use is 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 >
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.