首页 > 解决方案 > 多维数组按对象推送无法正常工作

问题描述

我有一个需要以特定方式格式化的数组,但它正在为其中一个对象生成一个随机键。请参阅下面的代码

$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来自哪里。请任何人根据我的预期答案更新我的代码。

标签: phpphp-7

解决方案


只是小小的改变。删除[Key]创建索引的部分,如 0、1。

因此,即使UID = 1001这是第一条记录,但由于循环,密钥位于 1,我们需要将其删除。

foreach ($temp as $key => $value) {
    $child[$value['UID']][] = ['UPID' => $value['UPID'], 'PID'=> $value['PID']];
}

推荐阅读