![](/img/trans.png)
[英]Any way to quickly define an array with the variable names as indexes in PHP?
[英]Is there any way to index an array with a sequence of indexes in a variable in PHP?
具有:數組$ a,變量$indexes = "[\\"level1\\"][\\"level2\\"][\\"level3\\"]"
;
有什么方法可以訪問$a["level1"]["level2"]["level3"]
嗎?
情況是此函數將處理的索引數可以更改。 因此,這就是索引進入變量的原因。
希望這個簡單的解決方案能對您有所幫助。
<?php
ini_set('display_errors', 1);
//Here we are retrieving levels
$indexes = '["level1"]["level2"]["level3"]';
preg_match_all('/(?<=")[\w]+(?=")/', $indexes,$matches);
$levels=$matches[0];
//this is the sample array
$array=$tempArray=array(
"level1"=>array(
"level2"=>array(
"level3"=>"someValue"
)
)
);
//here we are iterating over levels to get desired output.
foreach($levels as $level)
{
$tempArray=$tempArray[$level];
}
print_r($tempArray);
首先,不要將string
用於$indexes
,而要使用array
。
為了簡單的檢索,可以使用array_reduce
:
$result = array_reduce($indexes, function ($array, $index) {
return isset($array[$index]) ? $array[$index] : null;
}, $array);
請注意,如果數組中沒有這樣的索引,則值默認為null
。
這是工作演示 。
如果您需要一些更復雜的東西,請查看我一段時間前寫的一個庫,以了解情況,當您還需要向數組中添加項目並檢查是否存在時:
var_dump(isset($array[['foo', 'bar']]));
var_dump($array[['foo', 'bar']]);
$array[['foo', 'bar']] = 'baz';
unset($array[['foo', 'bar']]);
它們都是用於存在性檢查,檢索元素,寫入元素和刪除元素的有效用法示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.