简体   繁体   中英

Need help in array manipulation

Code Language : PHP

Actually i am not expert in array manipulation I have tried too much but didn't get success. Please check following array i want convert it.

I have this type of array

 [
      {
        "user_id": "1",
        "name": "A",
        "product": "Product A",
        "price": "456"
      },
      {
        "user_id": "1",
        "name": "A",
        "product": "Product B",
        "price": "255"
      },
      {
        "user_id": "1",
        "name": "A",
        "product": "Product C",
        "price": "111"
      },
      {
        "user_id": "2",
        "name": "B",
        "product": "Product D",
        "price": "888"
      },
      {
        "user_id": "2",
        "name": "B",
        "product": "Product E",
        "price": "408"
      }
    ]

I want to convert it to following

[
  {
    "user_id": "1",
    "name": "A",
    "product_data": [
      {
        "product": "Product A",
        "price": "456"
      },
      {
        "product": "Product B",
        "price": "255"
      },
      {
        "product": "Product C",
        "price": "111"
      }
    ]
  },
  {
    "user_id": "2",
    "name": "B",
    "product_data": [
      {
        "product": "Product D",
        "price": "888"
      },
      {
        "product": "Product E",
        "price": "408"
      }
    ]
  }
]

Please help me to solve out this..

You can achieve this by foreach() and array_key_exists() functions. Please see the below code, it may help you:

<?php

  $json ='[{
    "user_id": "1",
    "name": "A",
    "product": "Product A",
    "price": "456"
  },
  {
    "user_id": "1",
    "name": "A",
    "product": "Product B",
    "price": "255"
  },
  {
    "user_id": "1",
    "name": "A",
    "product": "Product C",
    "price": "111"
  },
  {
    "user_id": "2",
    "name": "B",
    "product": "Product D",
    "price": "888"
  },
  {
    "user_id": "2",
    "name": "B",
    "product": "Product E",
    "price": "408"
  }]';
  $source_array = json_decode($json);
  $result_arry = array();
  foreach($source_array as $entry)
  {
      if(array_key_exists($entry->user_id,$result_arry))
      {
                      $result_arry[$entry->user_id]['product_data'][] = array('product' => $entry->product,'price'=>$entry->price);
      }
      else
      {

        $result_arry[$entry->user_id] = array('user_id' =>$entry->user_id,'name'=>$entry->name,'product_data'=>array());
        $result_arry[$entry->user_id]['product_data'][] = array('product' => $entry->product,'price'=>$entry->price);
      }

  }
  print_r($result_arry);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM