在阵列操作方面需要帮助

时间:2016-09-22 11:40:43

标签: php arrays

代码语言:PHP

其实我不是数组操作方面的专家 我尝试过多,但没有成功。 请检查以下数组我想要转换它。

我有这种类型的数组

 [
      {
        "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"
      }
    ]

我想将其转换为以下

[
  {
    "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"
      }
    ]
  }
]

请帮我解决这个问题..

1 个答案:

答案 0 :(得分:1)

您可以通过foreach()和array_key_exists()函数实现此目的。请参阅以下代码,它可能会对您有所帮助:

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