php - 多维数组按对象推送无法正常工作
问题描述
我有一个需要以特定方式格式化的数组,但它正在为其中一个对象生成一个随机键。请参阅下面的代码
$temp = [
[
"UID" => "100",
"UPID" => "001",
"PID" => "test1"
],
[
"UID" => "1001",
"UPID" => "002",
"PID" => "test1"
]
];
$child = [];
foreach ($temp as $key => $value) {
$child[$value['UID']][$key]['UPID'] = $value['UPID'];
$child[$value['UID']][$key]['PID'] = $value['PID'];
}
$oldParentData['childUserProductDetail'] = $child;
echo "<pre>";
$result = json_encode($oldParentData, true);
print_r($result);
我的预期输出
{
"childUserProductDetail": {
"100": [
{
"UPID": "001",
"PID": "test1"
}
],
"1001": [
{
"UPID": "002",
"PID": "test1"
}
]
}
}
获得输出
{
"childUserProductDetail": {
"100": [
{
"UPID": "001",
"PID": "test1"
}
],
"1001": {
"1": { // See 1 as key here, that is unwanted
"UPID": "002",
"PID": "test1"
}
}
}
}
在这里,我不知道第二次数组没有创建和1
来自哪里。请任何人根据我的预期答案更新我的代码。
解决方案
只是小小的改变。删除[Key]
创建索引的部分,如 0、1。
因此,即使UID = 1001
这是第一条记录,但由于循环,密钥位于 1,我们需要将其删除。
foreach ($temp as $key => $value) {
$child[$value['UID']][] = ['UPID' => $value['UPID'], 'PID'=> $value['PID']];
}
推荐阅读
- r - 将 R 与 NodeJS 集成
- php - 如何在 laravel 中停止正在运行的排队作业?
- sorting - 如何在groovy中进行智能排序?
- sql - SQL- ORDER BY DESC 未正确获取结果
- swagger-ui - Swagger v3 - 从给定的一组值中选择多个值
- azure - 诊断日志(存储)未显示在 Azure 存储帐户中
- powerbi - 动态筛选器 - Power BI
- ios - 当其他单元格的动画完成时单元格中的动画停止
- android-studio - 列表视图隐藏在模拟器中
- excel - 如何将 PowerQuery 中的单个查询加载到工作簿中的多个工作表?