我们有一个多维关联数组。有必要寻址一个键上的数组元素,该键以其他线性数组写下来。
也就是说,有一个多维数据数组和一个带键的线性数组:
$a=[
'animals'=> [
'cats' => [
'catusdomesticus' => 'home',
'pantera' => 'wild'
]
]
];
$keys=['animals', 'cats', 'pantera'];
有两件事要做:
如何在PHP5中执行此操作?
注意:不需要代码生成和eval()。
UPD:
获得价值很容易:
$item =& $a;
foreach($keys as $key)
$item =& $item[$key];
var_dump( $item );
对于删除元素,我尝试下一个代码:
$item =& $a;
for($i=0; $i<count($keys); $i++)
{
$item =& $item[$keys[$i]];
if($i===count($keys)-1) {
echo "\nDelete element:\n";
var_dump($item);
unset($item);
}
}
var_dump( $a );
但这不起作用。 unset()引用数组值cant删除数组元素。
UPD2:
设置值的简短解决方案或从数组中删除元素:
$item =&$a;
foreach($keys as $key) {
$array =& $item;
$item =& $item[$key];
}
$array[$key] = 42; // For set value
OR
unset($array[$key]); // For remove element
答案 0 :(得分:1)
function get_value($keys, $a)
{
foreach($keys as $k)
{
if (isset($a[$k])
{
if (is_array($a[$k]))
{
return get_value($keys, $a[$k]);
}
else
{
return $a[$k];
}
}
}
return null; //nothing found
}
答案 1 :(得分:0)
这里有两种方法,我假设第二种方法会解决你最好的问题。
return ((Math.abs(strPartitionKey.hashCode())) % setNumRedTask);
答案 2 :(得分:0)
我们可以使用带有小调整的引用来删除数组值
$a=[
'animals'=> [
'cats' => [
'catusdomesticus' => 'home',
'pantera' => 'wild'
]
]
];
$keys=['animals', 'cats', 'pantera'];
$delItem = &$a;
foreach($keys as $key=>$val){
if($key == count($keys)-1)
$lastKey = $val;
else
$delItem = &$delItem[$val];
}
echo $delItem[$lastKey];//Get Value
unset($delItem[$lastKey]);//Remove Value
print_r($a);`