Home > Mobile >  Arrange items based on product id
Arrange items based on product id

Time:09-29

In the JSON file, there are multiple item based on the same product_id. I have to create multidimensional array based on product_id and items.

As per my sample php code, product_id is repeatedly listing. Results are printed in php code.

Expecting results are given below.

testData.json

"data": [
    {
      "product_id": "123456",
      "item": "ZAD",
      "time": "15:30",
      "quantity": 1
    },
    {
      "product_id": "24534"
      "item": "REST"
      "time": "5:30"
      "quantity": 1
    },
    {
      "product_id": "123456"
      "item": "RAD"
      "time": "10:30"
      "quantity": 2
    }
]

test.php

$json = file_get_contents('testData.json');

$d_data = json_decode($json, true);

$f_data = $d_data['data'];

foreach($f_data as $data) {
   $result = [
      $data['product_id'],
      $data['item']
   ]

   print_r($result); 
  /* Array(
          [0] => 123456 
          [1] => ZAD
     )
     Array(
          [0] => 123456 
          [1] => RAD
     )
     Array(
          [0] => 24534 
          [1] => REST
     )
  */
}

Expecting Result

123456
     [
        ZAD
           [
             "time" => "15:30",
             "quantity" => 1
           ],
        RAD
           [
            "time" => "10:30"
            "quantity" => 2
           ],
 ],
24534
    [
      REST
         [
           "time" => "5:30"
           "quantity" => 1
         ]
]
      

CodePudding user response:

You just need to account for both product_id and item as sub-keys in the final array:

$result = [];
foreach($f_data as $data) {
   $result[$data['product_id']][$data['item']] = [
      $data['time'],
      $data['quantity']
   ];
}

print_r($result);

Demo: https://3v4l.org/sf7om

I should note, if two items have the same product_id and same item, this code will only keep the last one. If that scenario applies to you, you just need to use the append mode ([]) of the array:

   $result[$data['product_id']][$data['item']][] = [
      $data['time'],
      $data['quantity']
   ];
  •  Tags:  
  • php
  • Related