問題描述
我正在嘗試用 php 編寫購物車,但在多維數組中獲取/設置值時遇到問題.我將當前訂單保存在 $_SESSION['basket']
中.看起來像這樣:
I am trying to write a shoping cart in php and I have a problem with get/set values in multidimentional arrays.
I keep the current order in $_SESSION['basket']
. It looks like that:
[basket] => Array
(
[0] => Array
(
[pid] => 3
[name] => Camera
[price] => 200.99
[quantity] => 1
)
[1] => Array
(
[pid] => 5
[name] => Computer
[price] => 320.99
[quantity] => 1
[extras] => Array
(
[0] => Array
(
[pid] => 86
[name] => RAM
[price] => 99
[qty] => 1
)
[1] => Array
(
[pid] => 98
[name] => CD-ROM
[price] => 19.99
[qty] => 1
)
)
)
)
每一項都存儲為一個子數組.我有一個函數,它檢查給定的項目是否存在于 basket
數組中并返回它的路徑.例如,如果我想檢查具有 id
98
(CD-Rom) 的產品,該函數返回以下路徑:1:extras:1代碼>.
Every item is stored as a subarray. I have a function, which checks if a given item exists in the basket
array and returns the path to it. For example, if I want to check for a product with id
98
(CD-Rom), the function returns the following path: 1:extras:1
.
如果我想在數組中獲取或設置一個值,我無法弄清楚如何使用路徑.是否可以在不使用 eval()
的情況下構造數組鍵的路徑?我有這些功能:
I cant figure out how to use the path if I want to get or a set a value in the array. Is it possible to construct the path to an array key, without the use of eval()
? I have these functions:
function get_val($array, $path, $key) {
//some code
return eval('return '.$array.$path.$key.';');
}
所以,$price = get_val($_SESSION['basket'], $path, 'price')
;應該返回 CD-ROM 的價格 (19.99)
So, $price = get_val($_SESSION['basket'], $path, 'price')
; should return the price for CD-ROM (19.99)
function set_val($array, $path, $key, $value) {
//some code
$str = eval(''.$array.$path.$key.';');
$str = $value;
}
set_val($_SESSION['basket'], $path, 'price', '30');
將 CD-ROM 的價格設置為 30.
set_val($_SESSION['basket'], $path, 'price', '30');
will set the price for CD-ROM to 30.
有沒有更好的方法來做到這一點?
Is there a better way for doing this?
謝謝.
推薦答案
這是我前段時間微調的代碼:
Here you go a code I have finetuned some time ago:
function get_val($array,$path) {
for($i=$array; $key=array_shift($path); $i=$i[$key]) {
if(!isset($i[$key])) return null;
}
return $i;
}
function set_val(&$array,$path,$val) {
for($i=&$array; $key=array_shift($path); $i=&$i[$key]) {
if(!isset($i[$key])) $i[$key] = array();
}
$i = $val;
}
看到這個測試示例,我相信這就是你要找的:
See this test example, I believe it is what you are looking for:
$data = array("x"=>array("y"=>array("z"=>"foo")));
echo get_val($data,array("x","y","z")); // foo
set_val($data,array("x","y","u"),"bar"); // $data["x"]["y"]["u"] = "bar";
這篇關于動態(tài)獲取/設置多維數組中的值的函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!