键名数组拼接

Array splice with key name

我有 2 个数组($data_1 和 $data_2),它们具有不同的值但有关系,我想合并这些数组,完全使用键名

$data_1 = 
'[
    {
        "fruit": "apple",
        "weight": "15"
    },
    {
        "fruit": "durian",
        "weight": "50"
    },
    {
        "fruit": "orange",
        "weight": "10"
    }
]';


$data_2 =
'[
    {
        "color": "red",
        "thorn": "no"
    },
    {
        "color": "green",
        "thorn": "yes"
    },
    {
        "color": "orange",
        "thorn": "no"
    }
]';

但我想合并这些数组,然后我有这样的完整数据:

$full_data = 
'[
    {
        "fruit": "apple",
        "weight": "15",
        "color": "red",
        "thorn": "no"
    },
    {
        "fruit": "durian",
        "weight": "50",
        "color": "green",
        "thorn": "yes"
    },
    {
        "fruit": "orange",
        "weight": "10",
        "color": "orange",
        "thorn": "no"
    }
]';

我试过 array_splice()

for ($i=0; $i < count($data_2); $i++) { 
    array_splice($data_1[$i], 0, 0, $data_2[$i]);
}

但它 returns '0' 和 '1' 不是原始密钥名称...

'[
    {
        "fruit": "apple",
        "weight": "15",
        "0": "red",
        "1": "no"
    },
    {
        "fruit": "durian",
        "weight": "50",
        "0": "green",
        "1": "yes"
    },
    {
        "fruit": "orange",
        "weight": "10",
        "0": "orange",
        "1": "no"
    }
]';

我想将“0”和“1”替换为原始键名

使用array_merge合并两个数组。

$full_data = [];
for ($i=0; $i < count($data_2); $i++) { 
    $full_data[$i] = array_merge($data_1[$i], $data_2[$i]);
}

简单地说,您可以通过

  1. 使用 json_decode 函数将两个数组格式 json 转换为两个 php 数组。
  2. 迭代其中一个并分别用两个数组的值填充$full_data
  3. 使用 json_encode 函数显示格式为 json 的数组。
// 1.
$data1 = json_decode($data_1,true);
$data2 = json_decode($data_2,true);

// 2.
$full_data = [];
for ($i=0; $i < count($data1); $i++) { 
    $full_data[$i] = $data1[$i] + $data2[$i];
}
// 3. 
echo(json_encode($full_data));
/*
[
 {"fruit":"apple","weight":"15","color":"red","thorn":"no"},
 {"fruit":"durian","weight":"50","color":"green","thorn":"yes"},
 {"fruit":"orange","weight":"10","color":"orange","thorn":"no"}
]
*/