[英]Convert a string into an associative array key?
給定一個包含由點分隔的值的字符串:
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}));
}
}
我想我可以將字符串轉換為可變變量,但我得到一個數組到字符串轉換錯誤。
您可以將字符串分解為數組並循環遍歷該數組。 ( 演示)
/**
* 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
將字符串拆分為多個部分,然后迭代數組,依次訪問每個元素:
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
現場示例: http : //codepad.viper-7.com/Vu8Hhy
在引用它們之前,您真的應該檢查鍵是否存在。 否則,您將發出大量警告。
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');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.