Nallammal T
Nallammal T

Reputation: 39

multidimensional array push an objectwise not working properly

I have one array which needs to formatted in specific way but it is generating a random key for one of the object. See my code below

$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);

my expected output

    {
  "childUserProductDetail": {
    "100": [
      {
        "UPID": "001",
        "PID": "test1"
      }
    ],
    "1001": [
       {
        "UPID": "002",
        "PID": "test1"
      }
    ]
  }
}

getting output

{

"childUserProductDetail": {
    "100": [
      {
        "UPID": "001",
        "PID": "test1"
      }
    ],
    "1001": {
      "1": {                                // See 1 as key here, that is unwanted
        "UPID": "002",
        "PID": "test1"
      }
    }
  }
}

Here i don't have idea second time array is not creating and 1 coming from where.kindly anyone update my code based on my expected answer.

Upvotes: 0

Views: 26

Answers (1)

Dark Knight
Dark Knight

Reputation: 6541

Just small change. Remove the [Key] section that is creating indexes like 0, 1.

So even for UID = 1001 this is first record, but due to loop the key is at 1 which we need to remove.

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

Upvotes: 1

Related Questions