给定一个包含以点分隔的值的字符串:
property.entry.item
将其转换为关联数组的键的最佳方法是什么?
$result['imported_data']['property']['entry']['item']
字符串可以是任意长度,任意数量的点并包含一个值:
people.arizona.phoenix.smith
我尝试了以下但没有成功:
//found a dot, means we are expecting output from a previous function
if( preg_match('[.]',$value)) {
//check for previous function output
if(!is_null($result['import'])) {
$chained_result_array = explode('.',$value);
//make sure we have an array to work with
if(is_array($chained_result_array)) {
$array_key = '';
foreach($chained_result_array as $key) {
$array_key .= '[\''.$key.'\']';
}
}
die(print_r(${result.'[\'import\']'.$array_key}));
}
}
我在想我可以将字符串转换为变量变量,但是我得到一个数组到字符串转换错误。
答案 0 :(得分:2)
您可以将字符串分解为数组并循环遍历数组。 (DEMO)
/**
* This is a test array
*/
$testArray['property']['entry']['item'] = 'Hello World';
/**
* This is the path
*/
$string = 'property.entry.item';
/**
* This is the function
*/
$array = explode('.', $string);
foreach($array as $i){
if(!isset($tmp)){
$tmp = &$testArray[$i];
} else {
$tmp = $tmp[$i];
}
}
var_dump( $tmp ); // output = Hello World
答案 1 :(得分:1)
将字符串拆分成部分,然后迭代数组,依次访问每个元素:
function arrayDotNotation($array, $dotString){
foreach(explode('.', $dotString) as $section){
$array = $array[$section];
}
return $array;
}
$array = ['one'=>['two'=>['three'=>'hello']]];
$string = 'one.two.three';
echo arrayDotNotation($array, $string); //outputs hello
答案 2 :(得分:1)
在引用密钥之前,您应该检查密钥是否存在。否则,你会发出很多警告。
function getProp($array, $propname) {
foreach(explode('.', $propname) as $node) {
if(isset($array[$node]))
$array = &$array[$node];
else
return null;
}
return $array;
}
现在你可以做以下事情:
$x = array(
'name' => array(
'first' => 'Joe',
'last' => 'Bloe',
),
'age' => 27,
'employer' => array(
'current' => array(
'name' => 'Some Company',
)
)
);
assert(getProp($x, 'age') == 27);
assert(getProp($x, 'name.first') == 'Joe');
assert(getProp($x, 'employer.current.name') == 'Some Company');
assert(getProp($x, 'badthing') === NULL);
assert(getProp($x, 'address.zip') === NULL);
或者,如果您只对树的import
部分感兴趣:
getProp($x['import'], 'some.path');