你好我有这样的数组,深度可变:
$array = [ // depth of array and number of values are variable
'this' => [
'a' => [
'b' => 'some value'
],
'c' => [
'd' => 'some value'
],
],
'that' => [
'path' => [
'to' => [
'val' => 'some value'
],
]
]
];
我需要这个:
$array['this.a.b'] => 'some value';
$array['this.c.d'] => 'some value';
$array['that.path.to.val'] => 'some value';
或者这可能更好:
$array[
0 => [
'key' => 'this.a.b',
'val' => 'some value'
],
1 => [
'key' => 'this.c.d',
'val' => 'some value'
],
2 => [
'key' => 'that.path.to.val',
'val' => 'some value'
],
]
我需要从数组中获取数据并将它们放到简单的形式,如:
<input name="this.a.b" value="some value">
我尝试过类似的东西,但效果并不好。
private static function reformat($input, $k = '', &$keys = [])
{
foreach($input as $key => $val) {
$k .= '.' . $key;
if (is_array($val)){
static::reformat($val, $k, $keys);
}else{
$keys[$k] = $val;
}
}
return $keys;
}
感谢您的帮助
答案 0 :(得分:0)
试试这个
$array['this']['a']['b'];
$array['this']['c']['d'];
$array['this']['path']['to']['val'];
或
function getVal($array, $key, $d='.') {
$keyArray = explode($d, $key);
$value = $array;
foreach($keyArray as $k){
if(isset($value[$k]))
$value = $value[$k];
else {
$value = "";
break;
}
}
return $value;
}
echo getVal($array, 'this.path.to.val');
答案 1 :(得分:0)
您可以让用户将功能定义为
$array = [
'this' => [
'a' => [
'b' => 'some value'
],
'c' => [
'd' => 'some value'
],
],
'that' => [
'path' => [
'to' => [
'val' => 'some value'
],
]
]
];
function makesingledimesional($arr,$par = ''){
$result = [];
$final = [];
foreach($arr as $key => $value){
if(is_array($value) && count($value)>0){
$par .= "$key.";
$result[$par] = makesingledimesional($value,$par);
}else{
$result[$par.$key] = $value;
}
}
array_walk_recursive($result,function($v,$k)use(&$final){$final[$k] = $v;});
return $final;
}
print_r(makesingledimesional($array));
<强>输出:强>
Array
(
[this.a.b] => some value
[this.a.c.d] => some value
[this.that.path.to.val] => some value
)
答案 2 :(得分:0)
我找到了想要的解决方案,现在是:
Array
(
[this.a.b] => some value
[this.c.d] => some value
[that.path.to.val] => some value
)
<强>输出强>
&