0

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.

1 Answer 1

1

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']];
}
Sign up to request clarification or add additional context in comments.

1 Comment

same UID have different UPID and PID so i need array here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.