我有这样一个数组:
[
{
"function_1": {
"element": {
"error": "0",
"msg": "test"
}
}
},
{
"function_1": {
"element_2": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element_2": {
"error": "0",
"msg": "test"
}
}
}
]我想要这样的产出:
[
{
"function_1": {
"element": {
"error": "0",
"msg": "test"
},
"element_2": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element": {
"error": "0",
"msg": "test"
},
"element_2": {
"error": "0",
"msg": "test"
}
}
}
]我找到的按名字搜索的答案(“function_1”,"function_2")。但是这不适合我,函数并不总是传递数组。我需要精确的“深度”或任何其他合理的方法。谢谢!
发布于 2022-11-20 21:03:18
为了达到您想要的结果,您可以使用json解码,递归地合并每个单独的子数组,然后循环遍历该结构,将每个项作为一个二级数组推送,如:(演示)。
$array = json_decode($json, true);
$merged = array_merge_recursive(...$array);
$result = [];
foreach ($merged as $key => $data) {
$result[] = [$key => $data];
}
var_export($result);但是,我无法想象在结果数组中增加不必要的深度会有什么好处。我推荐简单的json解码,然后用扩展操作符调用array_merge_recursive():(演示)
var_export(
array_merge_recursive(
...json_decode($json, true)
)
);输出:
array (
'function_1' =>
array (
'element' =>
array (
'error' => '0',
'msg' => 'test',
),
'element_2' =>
array (
'error' => '0',
'msg' => 'test',
),
),
'function_2' =>
array (
'element' =>
array (
'error' => '0',
'msg' => 'test',
),
'element_2' =>
array (
'error' => '0',
'msg' => 'test',
),
),
)发布于 2022-11-20 07:42:39
你的数据结构看起来很奇怪,因为你想达到的目的--我厌倦了,为你创建了这段代码
function combineElementsPerfunction($functions) {
$result = [];
$uniqueFunctions = [];
foreach ($functions as $function) {
$functionName = array_keys($function)[0];
$uniqueFunctions[] = $functionName;
}
$uniqueFunctions = array_unique($uniqueFunctions);
foreach ($uniqueFunctions as $uniqueFunction) {
$functionObjects = array_filter(
$functions,
function($function) use ($uniqueFunction) {
$functionName = array_keys($function)[0];
return $functionName === $uniqueFunction;
}
);
$elements = [];
foreach ($functionObjects as $functionObject) {
$function = array_shift($functionObject);
$elements = array_merge($elements, $function);
}
$result[] = [
$uniqueFunction => $elements
];
}
return $result;
}https://stackoverflow.com/questions/74506247
复制相似问题