我需要帮助才能找到当前代码的最佳实践答案。 感谢你的帮助。
如何以最佳方式遍历此数组:
$data = [
'element1.child.property1' => 1,
'element1.child.property2' => 2,
'element2.child.name' => 3,
'element2.child2.name' => 4,
'element2.child2.position' => 5,
'element3.child3.position' => 6,
];
得到这样的答案
$result = [
'element1' => [
'child' => [
'property1' => 1,
'property2' => 2,
]
],
'element2' => [
'child' => [
'name' => 3
],
'child2' => [
'name' => 4,
'position' => 5
]
],
'element3' => [
'child3' => [
'position' => 6
]
],
];
答案 0 :(得分:1)
你可以循环遍历数组并用"。"爆炸每个元素的键,然后填充你的新数组:
<?php
$data = [
'element1.child.property1' => 1,
'element1.child.property2' => 2,
'element2.child.name' => 3,
'element2.child2.name' => 4,
'element2.child2.position' => 5,
'element3.child3.position' => 6,
];
foreach ($data as $key => $value) {
$key = explode(".", $key);
$newData[$key[0]][$key[1]][$key[2]] = $value;
}
print_r($newData);
?>
这给了你:
Array
(
[element1] => Array
(
[child] => Array
(
[property1] => 1
[property2] => 2
)
)
[element2] => Array
(
[child] => Array
(
[name] => 3
)
[child2] => Array
(
[name] => 4
[position] => 5
)
)
[element3] => Array
(
[child3] => Array
(
[position] => 6
)
)
)
答案 1 :(得分:1)
这是你的数组:
$data = [
'element1.child.property1' => 1,
'element1.child.property2' => 2,
'element2.child.name' => 3,
'element2.child2.name' => 4,
'element2.child2.position' => 5,
'element3.child3.position' => 6,
];
1 /首先,创建一个结果数组:
$result = array();
2 /然后你将遍历你的数组并构建所需的输出:
foreach ($data as $key => $value) {
$elt = explode(".", $key);
// Here you will have :
// $elt[0] = "elementX";
// $elt[1] = "child";
// $elt[2] = "property1"; (OR "name" OR "position"...)
$result[$elt[0]][$elt[1]][$elt[2]] = $value;
}
3 /现在,如果您查看结果,他看起来就像您想要的输出:
var_dump($result);
$result = [
'element1' => [
'child' => [
'property1' => 1,
'property2' => 2,
]
],
'element2' => [
'child' => [
'name' => 3
],
'child2' => [
'name' => 4,
'position' => 5
]
],
'element3' => [
'child3' => [
'position' => 6
]
],
];
希望有所帮助
答案 2 :(得分:1)
对于可变长度和更深或更浅的嵌套更具动态性。您可以使用此函数并使用键作为路径和值来循环您的数组。结果将在$result
:
function set($path, &$array=array(), $value=null) {
$path = explode('.', $path);
$temp =& $array;
foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
}
foreach($data as $path => $value) {
set($path, $result, $value);
}
有关其他用途,请参阅How to access and manipulate multi-dimensional array by key names / path?。