问题描述
发现这个职位,帮助我了:Split一个字符串,形成多维数组的钥匙?
Found this post that helped me out: Split a string to form multidimensional array keys?
总之,工程就像一个魅力,当涉及到的字符串值,但是如果数组键包含整数,然后它忽略这些。
Anyhow that works like a charm when it comes to string values, but if array keys contain integers then it misses these.
下面是演示:
我得到了一组键的:
Array
(
[0] => variable_data
[1] => 0
[2] => var_type
)
和方法来创建电子邮件嵌套数组
And method to create e nested array
function constructArray( &$array_ptr, $keys, $value )
{
// extract the last key
$last_key = array_pop ( $keys );
// walk/build the array to the specified key
while ( $arr_key = strval( array_shift ( $keys ) ) )
{
if ( !array_key_exists ( strval($arr_key), $array_ptr ) )
{
$array_ptr[ strval($arr_key) ] = array ( );
}
$array_ptr = &$array_ptr[ strval($arr_key) ];
}
// set the final key
$array_ptr[ $last_key ] = '$value';
}
我用它是这样的:
And i use it in this way:
$keys = array(
'variable_data',
'0',
'var_type'
);
$clean_arr = array();
constructArray($clean_arr, $keys, 'asd');
但输出看起来是这样的:
but the output looks like this:
Array
(
[variable_data] => Array
(
[var_desc] => $value
)
)
正如你所见,variable_data指数不包含0指数。我已经测试了,我可能知道工作的allmost一切,但它没有。任何人谁拥有更好的线索?
As you see, variable_data index is not containing 0 index. I have tested allmost everything that i might know to work but it didnt. Anyone who has better clue ?
推荐答案
下面是一条什么神奇的功能:
Solution
Here's the function that does the magic:
function constructArray( &$array_ptr, $keys, $value )
{
// extract the last key
$last_key = array_pop ( $keys );
foreach ( $keys as $arr_key )
{
unset($keys[$arr_key]);
if ( !array_key_exists ( strval($arr_key), $array_ptr ) )
{
$array_ptr[ strval($arr_key) ] = array ( );
}
$array_ptr = &$array_ptr[ strval($arr_key) ];
}
// set the final key
$array_ptr[ $last_key ] = $value;
}
用法:
$keys = array('variable_data', '0', 'var_desc');
$clean_arr = array();
constructArray($clean_arr, $keys, 'asd');
// Output
Array
(
[variable_data] => Array
(
[0] => Array
(
[var_desc] => asd
)
)
)
这篇关于从组键PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!