我有一個這樣的陣列:
[
{
"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”)。但這不適合我,函式不會總是傳遞一個陣列。我需要確切的“深度”或任何其他合理的方式。謝謝!
uj5u.com熱心網友回復:
您的資料結構看起來很奇怪,因為您要達到的目的我很無聊,因此為您創建了這段代碼
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;
}
uj5u.com熱心網友回復:
function changeArr($data){
$box = $new = [];
foreach ($data as $v){
$key = array_key_first($v);
$i = count($box);
if(in_array($key, $box)){
$keys = array_flip($box);
$i = $keys[$key];
}else{
$box[] = $key;
}
$new[$i][$key] = isset($new[$i][$key]) ? array_merge($new[$i][$key], $v[$key]) : $v[$key];
}
return $new;
}
uj5u.com熱心網友回復:
為了達到你想要的結果,你可以 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()用傳播運算子呼叫:(Demo)
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',
),
),
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/537348.html
標籤:PHP数组合并
