我有一個包含陣列鍵位置的字串,我試圖使用該位置來訪問陣列 ($arr)。
字串 ($str) 的示例,其字串值為svg.1.linearGradient.0.@style
這將相當于 ['svg'][1]['linearGradient'][0]['@style']
如何使用字串從 $arr 使用上述位置訪問/檢索資料?
例如,假設我想取消設定陣列鍵unset($arr['svg'][1]['linearGradient'][0]['@style'])- 我如何以編程方式實作這一點?
uj5u.com熱心網友回復:
一種方法是在 上拆分字串.,然后遍歷“鍵”以遍歷您的$arr物件。(請原諒我可憐的php,已經有一段時間了......)
例子:
$arr = (object)[
"svg" => (array)[
(object)[],
(object)[
"linearGradient" => [
(object)[
"@style" => "testing",
],
],
],
],
];
$str = "svg.1.linearGradient.0.@style";
$keys = explode('.', $str);
$val = $arr;
foreach($keys as $key) {
$val = is_object($val)
? $val->$key
: $val[$key];
}
echo $val;
https://3v4l.org/h8YPv
取消設定給定路徑的鍵:
$arr = (object)[
"svg" => (array)[
(object)[],
(object)[
"linearGradient" => [
(object)[
"@style" => "testing",
],
],
],
],
];
$str = "svg.1.linearGradient.0.@style";
$keys = explode('.', $str);
$exp = "\$arr";
$val = $arr;
foreach($keys as $index => $key) {
$exp .= is_object($val)
? "->{'" . $key . "'}"
: "[" . $key . "]";
$val = is_object($val) ? $val->$key : $val[$key];
}
eval("unset($exp);");
https://3v4l.org/Fdo6B
檔案
- 爆炸()
- 評估()
uj5u.com熱心網友回復:
您可以使用通過參考傳遞值的機制:
$result = &$arr;
$path = explode('.', $str);
for($i = 0; $i < count($path); $i ) {
$key = $path[$i];
if (is_array($result) && array_key_exists($key, $result)) {
if ($i == count($path) - 1) {
unset($result[$key]); // deleting an element with the last key
} else {
$result = &$result[$key];
}
} else {
break; // not found
}
}
unset($result); // resetting value by reference
print_r($arr);
小提琴
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/326307.html
標籤:php
上一篇:增加共享主機中的PHP時間限制
